Getting messagingException
Hi,
I am writing a simple client program to read mail using IMAP protocol but , I am getting following exception. I did search on net but didn't find any solution . Please help me out.
javax.mail.MessagingException: A4 NO There is no replica for that mailbox on this server.;
nested exception is:
com.sun.mail.iap.CommandFailedException: A4 NO There is no replica for that mailbox on this server.
at com.sun.mail.imap.IMAPFolder.doCommand(IMAPFolder.java:2873)
at com.sun.mail.imap.IMAPFolder.exists(IMAPFolder.java:514)
at com.sun.mail.imap.IMAPFolder.checkExists(IMAPFolder.java:382)
at com.sun.mail.imap.IMAPFolder.open(IMAPFolder.java:934)
at readEmails.processMail(readEmails.java:60)
at readEmails.<init>(readEmails.java:20)
at readEmails.main(readEmails.java:166)
Caused by: com.sun.mail.iap.CommandFailedException: A4 NO There is no replica for that mailbox on this server.
at com.sun.mail.iap.Protocol.handleResult(Protocol.java:351)
at com.sun.mail.imap.protocol.IMAPProtocol.doList(IMAPProtocol.java:1100)
at com.sun.mail.imap.protocol.IMAPProtocol.list(IMAPProtocol.java:1046)
at com.sun.mail.imap.IMAPFolder$1.doCommand(IMAPFolder.java:516)
at com.sun.mail.imap.IMAPFolder.doProtocolCommand(IMAPFolder.java:2918)
at com.sun.mail.imap.IMAPFolder.doCommand(IMAPFolder.java:2868)
... 6 morefollowing is the code :
import javax.mail.AuthenticationFailedException;
import javax.mail.Folder;
import javax.mail.FolderClosedException;
import javax.mail.FolderNotFoundException;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.ReadOnlyFolderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.StoreClosedException;
import javax.mail.internet.InternetAddress;
public class readEmails {
//Constructor Call
public readEmails() {
processMail();
//Responsible for printing Data to Console
private void printData(String data) {
System.out.println(data);
public void processMail() {
Session session = null;
Store store = null;
Folder folder = null;
Message message = null;
Message[] messages = null;
Object messagecontentObject = null;
String sender = null;
String subject = null;
Multipart multipart = null;
Part part = null;
String contentType = null;
try {
printData("--------------processing mails started-----------------");
session = Session.getDefaultInstance(System.getProperties(), null);
printData("getting the session for accessing email.");
store = session.getStore("imap");
// store.connect("hostname","username","password");
store.connect("email.*******","***","****");
printData("Connection established with IMAP server.");
// Get a handle on the default folder
folder = store.getDefaultFolder();
printData("Getting the Inbox folder.");
// Retrieve the "Inbox"
folder = folder.getFolder("Inbox");
//Reading the Email Index in Read / Write Mode
folder.open(Folder.READ_ONLY);
// Retrieve the messages
messages = folder.getMessages();
// Loop over all of the messages
for (int messageNumber = 0; messageNumber <2; messageNumber++) {
// Retrieve the next message to be read
message = messages[messageNumber];
// Retrieve the message content
messagecontentObject = message.getContent();
// Determine email type
if (messagecontentObject instanceof Multipart) {
printData("Found Email with Attachment");
sender = ((InternetAddress) message.getFrom()[0]).getPersonal();
// If the "personal" information has no entry, check the address for the sender information
printData("If the personal information has no entry, check the address for the sender information.");
if (sender == null) {
sender = ((InternetAddress) message.getFrom()[0]).getAddress();
printData("sender in NULL. Printing Address:" + sender);
printData("Sender -." + sender);
// Get the subject information
subject = message.getSubject();
printData("subject=" + subject);
// Retrieve the Multipart object from the message
multipart = (Multipart) message.getContent();
printData("Retrieve the Multipart object from the message");
// Loop over the parts of the email
for (int i = 0; i < multipart.getCount(); i++) {
// Retrieve the next part
part = multipart.getBodyPart(i);
// Get the content type
contentType = part.getContentType();
// Display the content type
printData("Content: " + contentType);
if (contentType.startsWith("text/plain")) {
printData("---------reading content type text/plain mail -------------");
} else {
// Retrieve the file name
String fileName = part.getFileName();
printData("retrive the fileName="+ fileName);
} else {
printData("Found Mail Without Attachment");
sender = ((InternetAddress) message.getFrom()[0]).getPersonal();
// If the "personal" information has no entry, check the address for the sender information
printData("If the personal information has no entry, check the address for the sender information.");
if (sender == null) {
sender = ((InternetAddress) message.getFrom()[0]).getAddress();
printData("sender in NULL. Printing Address:" + sender);
// Get the subject information
subject = message.getSubject();
printData("subject=" + subject);
// Close the folder
folder.close(true);
// Close the message store
store.close();
} catch(AuthenticationFailedException e) {
printData("Not able to process the mail reading.");
e.printStackTrace();
} catch(FolderClosedException e) {
printData("Not able to process the mail reading.");
e.printStackTrace();
} catch(FolderNotFoundException e) {
printData("Not able to process the mail reading.");
e.printStackTrace();
} catch(NoSuchProviderException e) {
printData("Not able to process the mail reading.");
e.printStackTrace();
} catch(ReadOnlyFolderException e) {
printData("Not able to process the mail reading.");
e.printStackTrace();
} catch(StoreClosedException e) {
printData("Not able to process the mail reading.");
e.printStackTrace();
} catch (Exception e) {
printData("Not able to process the mail reading.");
e.printStackTrace();
//Main Function for The readEmail Class
public static void main(String args[]) {
//Creating new readEmail Object
readEmails readMail = new readEmails();
//Calling processMail Function to read from IMAP Account
//readMail.processMail();
}Edited by: Prem on May 12, 2013 2:43 PM
Are you using Microsoft Exchange?
I think you're running into "IMAP referrals" - a feature where the IMAP server can tell the client to
connect to a different server where the mailbox is really located. If you turn on JavaMail session
debugging and examine the protocol trace you might see the information about the referral.
Then you should be able to connect directly to the server it's referring you to.
Similar Messages
-
IOException: invalid content type for SOAP: TEXT/ using Sender SOAP adapter
Hi all,
When I am using Sender SOAP adapter, i am getting (MessagingException: Could not parse XMBMessage. Reason: java.io.IOException: invalid content type for SOAP: TEXT/HTML using connection SOAP_http://sap.com/xi/XI/System) exception.
From my RWB I can see:
2009-05-25 16:18:39 Information The message was successfully retrieved from the call queue.
2009-05-25 16:18:39 Information The message status was set to DLNG.
2009-05-25 16:18:39 Error Failed to parse the XI system response.
2009-05-25 16:18:39 Error The message was successfully transmitted to endpoint com.sap.engine.interfaces.messaging.api.exception.MessagingException: XIMessage creation failed (inbound). Reason: com.sap.engine.interfaces.messaging.api.exception.MessagingException: Could not parse XMBMessage. Reason: java.io.IOException: invalid content type for SOAP: TEXT/HTML using connection SOAP_http://sap.com/xi/XI/System.
2009-05-25 16:18:39 Error The message status was set to FAIL.
2009-05-25 16:18:39 Error Returning to application. Exception: com.sap.engine.interfaces.messaging.api.exception.MessagingException: XIMessage creation failed (inbound). Reason: com.sap.engine.interfaces.messaging.api.exception.MessagingException: Could not parse XMBMessage. Reason: java.io.IOException: invalid content type for SOAP: TEXT/HTML
Please help if possible! Thanks!
MayankHi,
Check in SLD your integration engine business system have the following
pipeline url : http://server:httpport/sap/xi/engine?type=entry
check Http port also
After that go to TCODE - SXMB_ADM - integrationn engine configuration and check if your server is configured as HUB with the same url or not.
Thanks
Kasturika Phukan -
Unable to send email to different domain by JavaMail
Hello,
I'm developing a servlet application by using using JavaMail 1.2 with JDK 1.3/Resin 1.2.
My application is hosted at an ASP. When I send email some addresses under my domain,
there is no problem. Emails are sent successfully. But, if I send emails to addresses under different domains, I get MessagingException in Transport.send(message) method.
My CGI scripts can successfully email messages to different domain.
thanks in advance...There is a Java Mail forum where you could have asked this. However, if you had looked there you would have found this question asked several times a week. Your ASP doesn't allow its e-mail system to be used for relaying. Ask the ASP if you don't understand what that means.
-
SMTP: retry send message
Hi All,
I have to implement email alerts as part of my application.(SMTP) I have to retry multiple times if the email is not sent successfully. I assume I have to retry if I get MessagingException or SendFailedException during Transport.send(). I only retry the validUnsent addresses in SendFailedException. Correct?
I couldn't find any info related to retry in http://www.oracle.com/technetwork/java/faq-135477.html
Thanks,
BinduNo.
Unless you enable "partial send", a send failure means that the message wasn't sent to any
of the recipients.
However, you probably want to do more analysis of the failure. If sending failed because one
of the recipients is invalid, retrying isn't likely to make any difference.
Generally the best approach is to make sure you're using a mail server that's at least as reliable
as your application, possibly colocated with your application, and let it handle all the messy retry
logic. If you can't talk to your local mail server, something is seriously wrong.
If you're stuck using a public mail server of questionable reliability, consider inserting your own
mail server between your application and it. -
Getting Exception of MessagingException
Hi All,
I am developing Email Application which retrieve the emails from the Gmail Account.
But I am getting the Exception:
1)
javax.mail.MessagingException: Connect failed; nested exception is: java.io.IOException: Couldn't connect using "javax.net.ssl.SSLSocketFactory" socket factory to host, port: pop.gmail.com, 995; Exception: java.lang.reflect.InvocationTargetException
2)
javax.mail.MessagingException: Not connected
Following is my program.
// This file has been generated partially by the Web Dynpro Code Generator.
// MODIFY CODE ONLY IN SECTIONS ENCLOSED BY @@begin AND @@end.
// ALL OTHER CHANGES WILL BE LOST IF THE FILE IS REGENERATED.
package com.sap.training;
// IMPORTANT NOTE:
// _ALL_ IMPORT STATEMENTS MUST BE PLACED IN THE FOLLOWING SECTION ENCLOSED
// BY @@begin imports AND @@end. FURTHERMORE, THIS SECTION MUST ALWAYS CONTAIN
// AT LEAST ONE IMPORT STATEMENT (E.G. THAT FOR IPrivateAccessGmailComp).
// OTHERWISE, USING THE ECLIPSE FUNCTION "Organize Imports" FOLLOWED BY
// A WEB DYNPRO CODE GENERATION (E.G. PROJECT BUILD) WILL RESULT IN THE LOSS
// OF IMPORT STATEMENTS.
//@@begin imports
import java.io.IOException;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.URLName;
import com.sap.training.wdp.IPrivateAccessGmailComp;
import com.sap.training.wdp.IPublicAccessGmailComp;
//@@end
//@@begin documentation
//@@end
public class AccessGmailComp
* Logging location.
private static final com.sap.tc.logging.Location logger =
com.sap.tc.logging.Location.getLocation(AccessGmailComp.class);
static
//@@begin id
String id = "$Id$";
//@@end
com.sap.tc.logging.Location.getLocation("ID.com.sap.tc.webdynpro").infoT(id);
* Private access to the generated Web Dynpro counterpart
* for this controller class. </p>
* Use <code>wdThis</code> to gain typed access to the context,
* to trigger navigation via outbound plugs, to get and enable/disable
* actions, fire declared events, and access used controllers and/or
* component usages.
* @see com.sap.training.wdp.IPrivateAccessGmailComp for more details
private final IPrivateAccessGmailComp wdThis;
* Root node of this controller's context. </p>
* Provides typed access not only to the elements of the root node
* but also to all nodes in the context (methods node<i>XYZ</i>())
* and their currently selected element (methods current<i>XYZ</i>Element()).
* It also facilitates the creation of new elements for all nodes
* (methods create<i>XYZ</i>Element()). </p>
* @see com.sap.training.wdp.IPrivateAccessGmailComp.IContextNode for more details.
private final IPrivateAccessGmailComp.IContextNode wdContext;
* A shortcut for <code>wdThis.wdGetAPI()</code>. </p>
* Represents the generic API of the generic Web Dynpro counterpart
* for this controller. </p>
private final com.sap.tc.webdynpro.progmodel.api.IWDComponent wdControllerAPI;
* A shortcut for <code>wdThis.wdGetAPI().getComponent()</code>. </p>
* Represents the generic API of the Web Dynpro component this controller
* belongs to. Can be used to access the message manager, the window manager,
* to add/remove event handlers and so on. </p>
private final com.sap.tc.webdynpro.progmodel.api.IWDComponent wdComponentAPI;
public AccessGmailComp(IPrivateAccessGmailComp wdThis)
this.wdThis = wdThis;
this.wdContext = wdThis.wdGetContext();
this.wdControllerAPI = wdThis.wdGetAPI();
this.wdComponentAPI = wdThis.wdGetAPI().getComponent();
//@@begin javadoc:wdDoInit()
/** Hook method called to initialize controller. */
//@@end
public void wdDoInit()
//@@begin wdDoInit()
//@@end
//@@begin javadoc:wdDoExit()
/** Hook method called to clean up controller. */
//@@end
public void wdDoExit()
//@@begin wdDoExit()
//@@end
//@@begin javadoc:wdDoPostProcessing()
* Hook called to handle data retrieval errors before rendering.
* After doModifyView(), the Web Dynpro Framework gets all context data needed
* for rendering by validating the contexts (which in turn calls the supply
* functions and supplying relation roles). In this hook, the application
* should handle the errors which occurred during validation of the contexts.
* Using preorder depth-first traversal, this hook is called for all component
* controllers starting with the current root component.
* Permitted operations:
* - Flushing model queue
* - Creating messages
* - Reading context and model data
* Forbidden operations:
* - Invalidating model data
* - Manipulating the context
* - Firing outbound plugs
* - Creating components
* @param isCurrentRoot true if this is the root of the current request
//@@end
public void wdDoPostProcessing(boolean isCurrentRoot)
//@@begin wdDoPostProcessing()
//@@end
//@@begin javadoc:wdDoBeforeNavigation()
* Hook before the navigation phase starts.
* This hook allows you to flush the model queue and handle any
* errors that occur. Firing outbound plugs is allowed in this hook.
* Using preorder depth-first traversal, this hook is called for all component
* controllers starting with the current root component.
* @param isCurrentRoot true if this is the root of the current request
//@@end
public void wdDoBeforeNavigation(boolean isCurrentRoot)
//@@begin wdDoBeforeNavigation()
//@@end
//@@begin javadoc:wdDoApplicationStateChange()
* Hook that informs the application about a state change.
* <p>
* This hook is called e.g. to tell the application that will be
* <ul>
* <li>left via a suspend plug and therefore should go into a suspend/sleep
* mode with minimal need of resources. errors that occur. Firing
* outbound plugs is allowed in this hook.
* <li>left due to a timeout and could write it's state to a data base if the
* user comes back later on
* </ul>
* The concrete reason is available via IWDApplicationStateChangeInfo
* <p>
* <b>Important</b>: This hook is called for the top level component only!
* @param stateChangeInfo contains the information about the nature of the state change
* @param stateChangeReturn allows the application to ask for a different state change.
* The framework is allowed to ignore it considering i.e. the current resources situation.
//@@end
public void wdDoApplicationStateChange(com.sap.tc.webdynpro.progmodel.api.IWDApplicationStateChangeInfo stateChangeInfo, com.sap.tc.webdynpro.progmodel.api.IWDApplicationStateChangeReturn stateChangeReturn)
//@@begin wdDoApplicationStateChange()
//@@end
//@@begin javadoc:Login()
/** Declared method. */
//@@end
public void Login( )
//@@begin Login()
try
Properties props = System.getProperties();
//props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.pop3.socketFactory.fallback", "false");
props.setProperty("mail.pop3.port", "995");
props.setProperty("mail.pop3.socketFactory.port", "995");
Session session = Session.getDefaultInstance(props,null);
URLName urln = new URLName("pop3","pop.gmail.com",995,null,
wdContext.nodeVnLogin().currentVnLoginElement().getVaUsername(),
wdContext.nodeVnLogin().currentVnLoginElement().getVaPassword());
store = session.getStore(urln);
store.connect();
wdComponentAPI.getMessageManager().reportSuccess("Suceesfully login");
catch(MessagingException e)
wdComponentAPI.getMessageManager().reportSuccess(e.toString());
//@@end
//@@begin javadoc:getInboxMsg()
/** Declared method. */
//@@end
public void getInboxMsg( )
//@@begin getInboxMsg()
try
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
message = folder.getMessages();
IPublicAccessGmailComp.IVnInboxElement inBoxElement;
for(int i=0;i<message.length;i++)
inBoxElement=wdContext.nodeVnInbox().createVnInboxElement();
inBoxElement.setVaFrom(message<i>.getFrom()[0].toString());
inBoxElement.setVaSubject(message<i>.getSubject());
// inBoxElement.setVaIndex(i);
wdContext.nodeVnInbox().addElement(inBoxElement);
wdComponentAPI.getMessageManager().reportSuccess("You have"+wdContext.nodeVnInbox().size()+"message");
wdContext.nodeVnInbox().setLeadSelection(-1);
catch(MessagingException e)
wdComponentAPI.getMessageManager().reportSuccess(e.toString());
//@@end
//@@begin javadoc:getTextContent()
/** Declared method. */
//@@end
public void getTextContent( )
//@@begin getTextContent()
try
String temp;
for(int j=0;j<wdContext.nodeVnInbox().size();j++)
if(j<0)
temp = "false";
else
temp = "true";
if(wdContext.nodeVnInbox().currentVnInboxElement().getVaIndex() == temp )
Object content = message[j].getContent();
Multipart multipart=(Multipart)content;
Part part=multipart.getBodyPart(0);
wdContext.currentContextElement().setCaBodyText(part.getContent().toString());
catch(MessagingException e)
wdComponentAPI.getMessageManager().reportSuccess(e.toString());
catch(IOException e)
wdComponentAPI.getMessageManager().reportSuccess(e.toString());
//@@end
//@@begin javadoc:Logout()
/** Declared method. */
//@@end
public void Logout( )
//@@begin Logout()
try
store.close();
catch(MessagingException e)
wdComponentAPI.getMessageManager().reportSuccess(e.toString());
//@@end
* The following code section can be used for any Java code that is
* not to be visible to other controllers/views or that contains constructs
* currently not supported directly by Web Dynpro (such as inner classes or
* member variables etc.). </p>
* Note: The content of this section is in no way managed/controlled
* by the Web Dynpro Designtime or the Web Dynpro Runtime.
//@@begin others
//final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Store store;
javax.mail.Message message[];
//@@end
Pls help me out asap
Thanks & Regards,
Dhruv Shah
Edited by: DS on Feb 20, 2008 3:06 PMHi Dhruv,
Are you sure you can connect to port 995 from the server?
Jeschael -
Suddenly getting exception - javax.mail.MessagingException: * BYE System
Hi,
Suddenly over the last week my application keeps throwing exceptions. This didnt happened before, so the code base hasnt changed! The exception I get is below. Tried searching the internet and tried what was suggested, but this hasnt helped.
javax.mail.MessagingException: * BYE System Error c63if10001534wej.179;
nested exception is:
com.sun.mail.iap.ConnectionException: * BYE System Error c63if10001534wej.179
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:616)
at javax.mail.Service.connect(Service.java:291)Just remembered that there are demos with the libraries. I used the msgshow.java example. I changed it so that is just dumped the messages size. I wrapped this in a script so that the msgshow app gets called a 100 times. Anyway I get the same result.
i.e.
done 45 times
Total messages = 444
New messages = 0
done 46 times
Total messages = 444
New messages = 0
done 47 times
Total messages = 445
New messages = 0
done 48 times
Total messages = 445
New messages = 0
done 49 times
Oops, got exception! * BYE System Error w20if10206000wem.32
javax.mail.MessagingException: * BYE System Error w20if10206000wem.32;
nested exception is:
com.sun.mail.iap.ConnectionException: * BYE System Error w20if10206000wem.32
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:668)
at javax.mail.Service.connect(Service.java:295)
at msgshow.main(msgshow.java:151)
Caused by: com.sun.mail.iap.ConnectionException: * BYE System Error w20if10206000wem.32
at com.sun.mail.iap.Protocol.handleResult(Protocol.java:356)
at com.sun.mail.imap.protocol.IMAPProtocol.login(IMAPProtocol.java:367)
at com.sun.mail.imap.IMAPStore.login(IMAPStore.java:728)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:648)
... 2 more
done 50 times
Total messages = 445
New messages = 0
done 51 times
Total messages = 445
New messages = 0
Hope someone can help with this. -
Getting an error in Dynamic Configuration
Hi Guys,
I need to dynamically post the file into different directories based on the file in the source payload.
In Receiver File Communication Channel
Target Directory : *
Filename : *
Checked the ASMA Attributes for filename and directory
Iam refering this weblog
/people/william.li/blog/2006/04/18/dynamic-configuration-of-some-communication-channel-parameters-using-message-mapping
In the mapping
<filename> ---> UDF --> topnode of target message.
My UDF is as below
public String Directory(String a,Container container){
DynamicConfiguration conf = (DynamicConfiguration) container.getTransformationParameters().get(StreamTransformationConstants.DYNAMIC_CONFIGURATION);
DynamicConfigurationKey key = DynamicConfigurationKey.create( "http://sap.com/xi/XI/System/File", "FileName");
DynamicConfigurationKey key1 = DynamicConfigurationKey.create( "http://sap.com/xi/XI/System/File", "Directory");
String FileName = conf.get(key);
FileName = a;
conf.put(key, FileName);
String Directory = conf.get(key1);
Directory = "/SAPInterface/XI/PPD/DHX/out";
conf.put(key1, Directory);
return " ";
But in runtime(moni) iam getting error as
com.sap.aii.af.ra.ms.api.MessagingException: The Adapter Message Property 'FileName' was configured as mandatory element, but there is no 'DynamicConfiguration' element in the XI Message header: com.sap.aii.adapter.file.configuration.DynamicConfigurationException: The Adapter Message Property 'FileName' was configured as mandatory element, but there is no 'DynamicConfiguration' element in the XI Message header
Please suggest me how to correct this.
Thanks
SrinivasHi Srinivas,
You said you are having dynamic directories to post the file. But I see you hardcorded or put constant for directory which is /SAPInterface/XI/PPD/DHX/out. I think you need to put //SAPInterface/XI/PPD/DHX/out.
Try this in udf:
public String Directory(String a,Container container){
DynamicConfiguration conf = (DynamicConfiguration) container.getTransformationParameters().get(StreamTransformationConstants.DYNAMIC_CONFIGURATION);
DynamicConfigurationKey key = DynamicConfigurationKey.create( "http://sap.com/xi/XI/System/File", "FileName");
DynamicConfigurationKey key1 = DynamicConfigurationKey.create( "http://sap.com/xi/XI/System/File", "Directory");
String FileName = conf.get(key);
FileName = a;
conf.put(key, FileName);
Directory = "//SAPInterface/XI/PPD/DHX/out";
conf.put(key1, Directory);
return " ";
Put FileName and Directory in file name and directory paramters in receiver communication cahnnel and cehck.
Regards,
--Satish -
How to get All Mails from outlook
Hi am reading mail from outlook.. It reads only unread mails. But i want to read all mails. if any one knows please help me..My code is..
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
public class AllPartsClient {
public static void main(String[] args) {
Properties props = new Properties();
String host = "myhost";
String username = "myuser";
String password = "mypass";
String provider = "pop3";
try {
Session session = Session.getDefaultInstance(props, null);
// Connect to the server and open the folder
Store store = session.getStore(provider);
store.connect(host, username, password);
Folder folder = store.getFolder("INBOX");
if (folder == null) {
System.out.println("Folder " + folder.getFullName() + " not found.");
System.exit(1);
folder.open(Folder.READ_ONLY);
// Get the messages from the server
Message[] messages = folder.getMessages();
for (int i = 0; i < messages.length; i++) {
System.out.println("------------ Message " + (i+1)
+ " ------------");
// Print message headers
Enumeration headers = messages.getAllHeaders();
while (headers.hasMoreElements()) {
Header h = (Header) headers.nextElement();
System.out.println(h.getName() + ": " + h.getValue());
System.out.println();
// Enumerate parts
Object body = messages[i].getContent();
if (body instanceof Multipart) {
processMultipart((Multipart) body);
else { // ordinary message
processPart(messages[i]);
System.out.println();
// Close the connection
// but don't remove the messages from the server
folder.close(true);
catch (Exception e) {
e.printStackTrace();
// Since we may have brought up a GUI to authenticate,
// we can't rely on returning from main() to exit
System.exit(0);
public static void processMultipart(Multipart mp)
throws MessagingException {
System.out.println("mp.getCount() = "+mp.getCount());
for (int i = 0; i < mp.getCount(); i++) {
processPart(mp.getBodyPart(i));
public static void processPart(Part p) {
try {
String fileName = p.getFileName();
String disposition = p.getDisposition();
String contentType = p.getContentType();
if (fileName == null && (Part.ATTACHMENT.equals(disposition)
|| !contentType.equalsIgnoreCase("text/plain"))) {
// pick a random file name. This requires Java 1.2 or later.
fileName = File.createTempFile("attachment", ".txt").getName();
if (fileName == null) { // likely inline
p.writeTo(System.out);
else {
File f = new File(fileName);
// find a version that does not yet exist
for (int i = 1; f.exists(); i++) {
String newName = fileName + " " + i;
f = new File(newName);
FileOutputStream out = new FileOutputStream(f);
// We can't just use p.writeTo() here because it doesn't
// decode the attachment. Instead we copy the input stream
// onto the output stream which does automatically decode
// Base-64, quoted printable, and a variety of other formats.
InputStream in = new BufferedInputStream(p.getInputStream());
int b;
while ((b = in.read()) != -1) out.write(b);
out.flush();
out.close();
in.close();
catch (Exception e) {
System.err.println(e);
e.printStackTrace();
In this code if Content is Multipart then it is not displaying content..
ThanksHi
if i use String provider = "imap"; then it shows the following error message..
javax.mail.MessagingException: Connection refused: connect
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:479)
at javax.mail.Service.connect(Service.java:275)
at javax.mail.Service.connect(Service.java:156)
at javamail.AllPartsClient.main(AllPartsClient.java:39)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:364)
at java.net.Socket.connect(Socket.java:507)
at java.net.Socket.connect(Socket.java:457)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
at com.sun.mail.iap.Protocol.<init>(Protocol.java:84)
at com.sun.mail.imap.protocol.IMAPProtocol.<init>(IMAPProtocol.java:87)
at com.sun.mail.imap.IMAPStore.protocolConnect(IMAPStore.java:446)
... 3 more
pls any one give idea -
How to get the output of a program into the email program.
hi
i had created a java mail program and the keygeneration program.seperately.
i want to get the keygeneration into my email program.that should be sent along with the text message.so pls help me in this regared.
i had pasted my coding her
email pgm.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
To use this program, change values for the following three constants,
SMTP_HOST_NAME -- Has your SMTP Host Name
SMTP_AUTH_USER -- Has your SMTP Authentication UserName
SMTP_AUTH_PWD -- Has your SMTP Authentication Password
Next change values for fields
emailMsgTxt -- Message Text for the Email
emailSubjectTxt -- Subject for email
emailFromAddress -- Email Address whose name will appears as "from" address
Next change value for "emailList".
This String array has List of all Email Addresses to Email Email needs to be sent to.
Next to run the program, execute it as follows,
SendMailUsingAuthentication authProg = new SendMailUsingAuthentication();
public class SendMailUsingAuthentication
private static final String SMTP_HOST_NAME = "smtp.mail.yahoo.com";
private static final String SMTP_AUTH_USER = "xxxx";
private static final String SMTP_AUTH_PWD = "xxxx";
//private static final String emailMsgTxt = "Online Order Confirmation Message. Also include the Tracking Number.";
private static final String emailSubjectTxt = "Order Confirmation Subject";
private static final String emailFromAddress = "[email protected]";
private static String emailMsgTxt = "I am unable to attend to your message, as I am busy sunning"
+ "myself on the beach in Maui, where it is warm and peaceful."
+ "Perhaps when I return I'll get around to reading your mail."
+ "Or perhaps not.";
private static final String[] emailList = { "[email protected]","[email protected]"};
public static void main(String args[]) throws Exception
SendMailUsingAuthentication smtpMailSender = new SendMailUsingAuthentication();
smtpMailSender.postMail( emailList, emailSubjectTxt, emailMsgTxt, emailFromAddress);
System.out.println("Sucessfully Sent mail to All Users");
public void postMail( String recipients[ ], String subject,
String message , String from) throws MessagingException
boolean debug = true;
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST_NAME);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "25");
props.put("mail.smtp.protocol","smtp");
props.put("mail.debug", "true");
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getDefaultInstance(props, auth);
session.setDebug(debug);
// create a message
Message msg = new MimeMessage(session);
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++)
addressTo[i] = new InternetAddress(recipients);
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
private class SMTPAuthenticator extends javax.mail.Authenticator
public PasswordAuthentication getPasswordAuthentication()
String username = SMTP_AUTH_USER;
String password = SMTP_AUTH_PWD;
return new PasswordAuthentication(username, password);
keygeneration program:
import java.io.Serializable;
import java.security.Security;
import com.sun.net.ssl.*;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
public class Eval {
public static void main(String args[]) throws Exception {
String inputString ="0x0b0b0b0b";
KeyGenerator keyGen = KeyGenerator.getInstance("HMACMD5");
SecretKey secretKey = keyGen.generateKey();
Mac mac = Mac.getInstance(secretKey.getAlgorithm());
mac.init(secretKey);
byte[] byteData = inputString.getBytes("UTF8");
byte[] macBytes = mac.doFinal(byteData);
String macAsString = new sun.misc.BASE64Encoder().encode(macBytes);
System.out.println("Authentication code is: " + macAsString);I'm not sure what's confusing you. Just generate a String (using a StringBuffer)
with the data you need and use it as the content of the mail message. If each
recipient needs different content, they'll each need a different MimeMessage
object. -
Can't get the attachment filename out of a Part (with non ascii characters)
Hello, all and happy new year :)
My issue is with non ascii filename in attachments... Yes i've read the FAQ : http://www.oracle.com/technetwork/java/faq-135477.html#encodefilename
I can't get the filename out of the BodyPart for those kind of attachments
here's my unit test :
* contains various parts from various mailer encoded in different ways...
private enum EncodedFileNamePart{
OUTLOOK("Content-Type: text/plain;\n name=\"=?iso-8859-1?Q?c'estd=E9j=E0no=EBl=E7ac'estcool.txt?=\" \nContent-Transfer-Encoding: 7bit\nContent-Disposition: attachment;\n filename=\"=?iso-8859-1?Q?c'estd=E9j=E0no=EBl=E7ac'estcool.txt?=\" \n\nnoel 2010\n","c'estdéjànoëlçac'estcool.txt"),
GMAIL("Content-Type: text/plain; charset=US-ASCII; name=\"=?ISO-8859-1?B?ZOlq4G5v62znYWNlc3Rjb29sLnR4dA==?=\"\nContent-Disposition: attachment; filename=\"=?ISO-8859-1?B?ZOlq4G5v62znYWNlc3Rjb29sLnR4dA==?=\"\nContent-Transfer-Encoding: base64\nX-Attachment-Id: f_giityr5r0\n\namluZ2xlIGJlbGxzIQo=\n","déjànoëlçacestcool.txt"),
THUNDERBIRD("Content-Type: text/plain;\n name=\"=?ISO-8859-1?Q?d=E9j=E0no=EBl=E7acestcool=2Etxt?=\"\nContent-Transfer-Encoding: 7bit\nContent-Disposition: attachment;\n filename*0*=ISO-8859-1''%64%E9%6A%E0%6E%6F%EB%6C%E7%61%63%65%73%74%63%6F;\n filename*1*=%6F%6C%2E%74%78%74\n\njingle bells!\n","déjànoëlçacestcool.txt"),
EVOLUTION("Content-Disposition: attachment; filename*=ISO-8859-1''d%E9j%E0no%EBl.txt\nContent-Type: text/plain; name*=ISO-8859-1''d%E9j%E0no%EBl.txt; charset=\"UTF-8\" \nContent-Transfer-Encoding: 7bit\n\njingle bells\n","déjànoël.txt"),
String content=null;
String target=null;
private EncodedFileNamePart(String content,String target){
this.content=content;
this.target=target;
public Part get(){
try{
ByteArrayInputStream bis = new ByteArrayInputStream(this.content.getBytes());
Part part = new MimeBodyPart(bis);
bis.close();
return part;
catch(Throwable e){
return null;
public String getTarget(){
return this.target;
@Test
public void testJavamailDecode() throws MessagingException, UnsupportedEncodingException{
System.setProperty("mail.mime.encodefilename", "true");
System.setProperty("mail.mime.decodefilename", "true");
for(EncodedFileNamePart part : EncodedFileNamePart.values())
assertEquals(part.name(),MimeUtility.decodeText(part.get().getFileName()),part.getTarget());
I take a NullPointerExcepion in the decodeText because getFileName() return null for the EVOLUTION case, and work well with OUTLOOK, THUNDERBIRD and GMAIL.
Evolution's content type is "Content-Disposition: attachment; filename*=ISO-8859-1''d%E9j%E0no%EBl.txt" wich doesn't look like the other (looks like the RFC 2616 or RFC5987 to do it.)
How can i handle this situation except by writting my own decoder?
Thanks for your answers!
Edited by: user13619058 on 4 janv. 2011 07:44Set the System property "mail.mime.decodeparameters" to "true" to enable the RFC 2231 support.
See the javadocs for the javax.mail.internet package for the list of properties.
Yes, the FAQ entry should contain those details as well. -
How can I get a SOAP Error message in ABAP ?
Dear all.
I'm trying to get SOAP Error message during XI Interface.
I've got an Error ( T-code : sxi_monitor ) and I need to get the Error message and write to screen.
I used
CATCH CX_AI_APPLICATION_FAULT.
CATCH CX_AI_SYSTEM_FAULT.
but couldn't get the error message.
The Error occured as below.
<SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="1">
<SAP:Category>XIAdapterFramework</SAP:Category>
<SAP:Code area="MESSAGE">GENERAL</SAP:Code>
<SAP:P1 />
<SAP:P2 />
<SAP:P3 />
<SAP:P4 />
<SAP:AdditionalText>com.sap.engine.interfaces.messaging.api.exception.MessagingException: Error processing request in sax parser: Error when executing statement for table/stored proc. 'ZTSD0030' (structure 'stmt1'): java.sql.SQLException: FATAL ERROR: Column 'ORDER' does not exist in table 'ZTSD0030'</SAP:AdditionalText>
<SAP:ApplicationFaultMessage namespace="" />
<SAP:Stack />
<SAP:Retry>M</SAP:Retry>
</SAP:Error>
I exactly need 'BOLD' style message.
Any help is appreciated.
Thanks!Hi,
This is an application fault,
error log clearly saying that''ORDER' does not exist in table 'ZTSD0030'.
these are specific to interfaces, in order to handle those
u need to configure apllication log at 'SLG1' t.code.
i mean, u have to use following function moules to handle application log in ABAP Proxy .
i.e
APPL_LOG_WRITE_HEADER
APPL_LOG_WRITE_MESSAGES
APPL_LOG_WRITE_DB.
warm regards
mahesh. -
Error getting while calling a webService from XI
Hi
We are getting the follwoing error while calling a webservice from XI. We Could call the same webservice from XML spy. Have checked the SOAP adapter it was running fine and the communication channel parameters too.
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?><!-- Inbound Message --> <SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="1"><SAP:Category>XIAdapterFramework</SAP:Category><SAP:Code area="MESSAGE">GENERAL</SAP:Code><SAP:P1/><SAP:P2/><SAP:P3/><SAP:P4/><SAP:AdditionalText>com.sap.aii.af.ra.ms.api.MessagingException: SOAP: response message contains an error Application/UNKNOWN/APPLICATION_ERROR - application fault: com.sap.aii.af.ra.ms.api.RecoverableException: SOAP: response message contains an error Application/UNKNOWN/APPLICATION_ERROR - application fault</SAP:AdditionalText><SAP:ApplicationFaultMessage namespace=""/><SAP:Stack/><SAP:Retry>M</SAP:Retry></SAP:Error>
Please try to help.
Thanks
RameshHi
Thanks a lot for your kind support.
Hi Moorthy
We have created one Asyn MI and wrapped the external definition into that, Haven't done any mapping for responce. Please find the trace below.
Hi Bhavesh
It was great helpful link but the payload days is not visible for this message it was containing details about sending. For some other message i could see payload.
I Could see one differnce in the XML Spy and "XI payload before entering SOAP Adapter"
The following line doesnt appear in the XI payload.
<m:StatusUpdate xmlns:m="http://localhost/StatusUpdate" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
</m:StatusUpdate>
Is this line would be embeded in the SOAP Adapter??? Please find the trace below. Please help me if you have any additional info.
The message was successfully received by the messaging system. Profile: XI URL: Using connection AFW. Trying to put the message into the receive queue.
Message successfully put into the queue.
The message was successfully retrieved from the receive queue.
The message status set to DLNG.
Delivering to channel: CC_SOAP_Rcvr_D_Pick_ZALEAUD
SOAP: request message entering the adapter
SOAP: completed the processing
SOAP: response message received 4cb3fab0-7fc5-11db-8c5a-000f203c93e0
SOAP: response message contains an error Application/UNKNOWN/APPLICATION_ERROR - application fault
SOAP: sending a delivery error ack ...
SOAP: sent a delivery error ack
Exception caught by adapter framework: SOAP: response message contains an error Application/UNKNOWN/APPLICATION_ERROR - application fault
Delivery of the message to the application using connection AFW failed, due to: SOAP: response message contains an error Application/UNKNOWN/APPLICATION_ERROR - application fault.
The asynchronous message was successfully scheduled to be delivered at Wed Nov 29 16:23:51 GMT 2006.
The message status set to WAIT.
Retrying to deliver message to the application. Retry: 1
Kind Regards
Ramesh
Message was edited by:
Ramesh Reddy Pothireddy -
Getting error when sending SMTP mail using javamail api
hi all
i am new to javamail api...and using it first-time....i'v used the following code
<%
String mailHost="mail.mastsale.com";
String mailText="Hello this is a test msg";
String to="<a href="mailto:[email protected]">[email protected]</a>";
String subject="jsp test mail";
try
String from="<a href="mailto:[email protected]">[email protected]</a>";
String mailhost = "mail.mastsale.com";
Properties props = System.getProperties();
props.put("mail.smtp.host", mailhost);
// Get a Session object
Authenticator auth = new SMTPAuthenticator( "<a href="mailto:[email protected]">[email protected]</a>", "abcd" );
Session session1 = Session.getInstance(props,auth);
//Session.setDebug(true);
//construct message
Message msg = new MimeMessage(session1);
msg.setFrom(new InternetAddress(from,"Your Name"));
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
msg.setSubject(subject);
msg.setText(mailText);
//msg.setHeader("X-Mailer",mailer);
msg.setSentDate(new Date());
msg.saveChanges();
//Send the message
out.println("Sending mail to " + to);
Transport.send(msg);
catch (MessagingException me)
out.println("Error in sending message for messaging exception:"+me);
%>
and
SMTPAuthenticator.java
import java.io.*;
import java.util.*;
import java.lang.*;
import javax.mail.*;
import javax.mail.internet.*;
public class SMTPAuthenticator extends javax.mail.Authenticator {
private String fUser;
private String fPassword;
public SMTPAuthenticator(String user, String password) {
fUser = user;
fPassword = password;
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fUser, fPassword);
Now getting error as: Error in sending message for messaging exception:javax.mail.SendFailedException: Invalid Addresses; nested exception is: com.sun.mail.smtp.SMTPAddressFailedException: 550-(host.hostonwin.com) [208.101.41.106] is currently not permitted to relay 550-through this server. Perhaps you have not logged into the pop/imap server 550-in the last 30 minutes or do not have SMTP Authentication turned on in your 550 email client.
Can anyone help me?i got the following error while using the below code,
-----------registerForm----------------
DEBUG: setDebug: JavaMail version 1.3.2
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Sun Microsystems, Inc]
DEBUG SMTP: useEhlo true, useAuth true
:::::::::::::::::::::::::::::::::<FONT SIZE=4 COLOR="blue"> <B>Error : </B><BR><HR> <FONT SIZE=3 COLOR="black">javax.mail.AuthenticationFailedException<BR><HR>
-----------registerForm----------------
public class SendMailBean {
public String send(String p_from, String p_to, String p_cc, String p_bcc,
String p_subject, String p_message, String p_smtpServer,String FilePath) {
String l_result = "";
// Name of the Host machine where the SMTP server is running
String l_host = p_smtpServer;
//for file attachment
String filename = FilePath;
// Gets the System properties
Properties l_props = System.getProperties();
// Puts the SMTP server name to properties object
l_props.put("mail.smtp.host", l_host);
l_props.put("mail.smtp.auth", "true");
// Get the default Session using Properties Object
Session l_session = Session.getDefaultInstance(l_props, null);
l_session.setDebug(true); // Enable the debug mode
try {
MimeMessage l_msg = new MimeMessage(l_session); // Create a New message
l_msg.setFrom(new InternetAddress(p_from)); // Set the From address
// Setting the "To recipients" addresses
l_msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(p_to, false));
// Setting the "Cc recipients" addresses
l_msg.setRecipients(Message.RecipientType.CC,
InternetAddress.parse(p_cc, false));
// Setting the "BCc recipients" addresses
l_msg.setRecipients(Message.RecipientType.BCC,
InternetAddress.parse(p_bcc, false));
l_msg.setSubject(p_subject); // Sets the Subject
// Create and fill the first message part
MimeBodyPart l_mbp = new MimeBodyPart();
//123
///////l_mbp.setText(p_message);
l_mbp.setContent(p_message,"text/html");
// Create the Multipart and its parts to it
Multipart l_mp = new MimeMultipart();
//l_mp.setContent(html,"text/html");
l_mp.addBodyPart(l_mbp);
// Add the Multipart to the message
l_msg.setContent(l_mp,"text/html");
// Set the Date: header
l_msg.setSentDate(new Date());
//added by cibijaybalan for file attachment
// attach the file to the message
//Multipart l_mp1 = new MimeMultipart();
if(!filename.equals(""))
String fname = filename;
MimeBodyPart mbp2 = new MimeBodyPart();
FileDataSource fds = new FileDataSource(fname);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());
l_mp.addBodyPart(mbp2);
// add the Multipart to the message
l_msg.setContent(l_mp);
//ends here
l_msg.setSentDate(new java.util.Date());
// Send the message
Transport.send(l_msg);
// If here, then message is successfully sent.
// Display Success message
l_result = l_result + "Mail was successfully sent to : "+p_to;
//if CCed then, add html for displaying info
//if (!p_cc.equals(""))
//l_result = l_result +"<FONT color=green><B>CCed To </B></FONT>: "+p_cc+"<BR>";
//if BCCed then, add html for displaying info
//if (!p_bcc.equals(""))
//l_result = l_result +"<FONT color=green><B>BCCed To </B></FONT>: "+p_bcc ;
//l_result = l_result+"<BR><HR>";
} catch (MessagingException mex) { // Trap the MessagingException Error
// If here, then error in sending Mail. Display Error message.
l_result = l_result + "<FONT SIZE=4 COLOR=\"blue\"> <B>Error : </B><BR><HR> "+
"<FONT SIZE=3 COLOR=\"black\">"+mex.toString()+"<BR><HR>";
} catch (Exception e) {
// If here, then error in sending Mail. Display Error message.
l_result = l_result + "<FONT SIZE=4 COLOR=\"blue\"> <B>Error : </B><BR><HR> "+
"<FONT SIZE=3 COLOR=\"black\">"+e.toString()+"<BR><HR>";
e.printStackTrace();
}//end catch block
//finally {
System.out.println(":::::::::::::::::::::::::::::::::"+l_result);
return l_result;
} // end of method send
} //end of bean
plz help me -
I'm getting an exception while sending a mail . .
i'm get an excpetion while sending a mail, example i'm getting
this particular error
Exception in thread "main" java.lang.NoClassDefFoundError: javax/activation/DataSource
at MailTest.<init>(MailTest.java:25)
at MailTest.main(MailTest.java:42)
this is my code
pls help me out
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import javax.naming.Context;
import javax.naming.InitialContext;
public class MailTest
String mailHost = "mail.business-functions.com";
String to = "[email protected]";
String from = "[email protected]";
String subject = "This is Test Mail Thru Java Mail API";
String body = "This is Test Mail to check whether the Java Mail APi is Working or not. This is prototype developed by Snehal K gandhi of Business Functions Software Solutions Pvt Ltd.";
Provider provider;
public MailTest()
try
Properties props = System.getProperties();
props.put("mail.smtp.host", mailHost);
Session session = Session.getInstance(props,null);
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,new InternetAddress[]{new InternetAddress(to)});
message.setSubject(subject);
message.setContent(body, "text/plain");
Transport.send(message);
System.out.println("Mail has been Sent");
catch(MessagingException me)
System.out.println("2. Error While Sending the Mail and the exception is : " + me.toString());
public static void main(String arg[])
new MailTest();
***********************************************************************/<sigh>
You need activation.jar in your classpath and or
import javax.activation.*;
See the JavaMail Readme for more info.
If you haven't got JAF get it here
http://java.sun.com/products/javabeans/glasgow/jaf.html
Rgds,
SH -
I am trying to get hotmail emails and store in Oracle 10g database.
When I am executing receivemail procedure from Oracle 10g database. I am getting following error.
connect to ESIMSCO_UTIL_OWNER
SQL> set serveroutput on
SQL>
SQL> Declare
2 v_error_msg varchar2(10000);
3 Begin
4 v_error_msg:=receivemail('pop3.live.com', '<My email address>@hotmail.com', '<My email password>');
5 dbms_output.put_line(v_error_msg);
6 End;
7 /
javax.mail.AuthenticationFailedException: EOF on socket
PL/SQL procedure successfully completed.
SQL>
I did following steps, but still I am getting this error. Can somebady help me to solve this problem.
connect sys/<password>@esimsco as sysdba
connect to sys
SQL*Plus: Release 10.2.0.1.0 - Production on Wed May 30 16:02:04 2012
Copyright (c) 1982, 2005, Oracle. All rights reserved.
Connected to:
Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
With the Partitioning, OLAP and Data Mining options
SQL> begin
1 dbms_java.grant_permission( 'ESIMSCO_UTIL_OWNER', 'SYS:java.util.PropertyPermission', '*', 'read,write' );
2 commit;
3 end;
4 /
PL/SQL procedure successfully completed.
SQL> begin
2 dbms_java.grant_permission(
3 grantee => 'ESIMSCO_UTIL_OWNER',
4 permission_type => 'SYS:java.net.SocketPermission',
5 permission_name => '*',
6 permission_action => 'connect,resolve'
7 );
8 end;
9 /
PL/SQL procedure successfully completed.
SQL> begin
2 dbms_java.grant_permission(
3 grantee => 'ESIMSCO_UTIL_OWNER',
4 permission_type => 'SYS:java.util.PropertyPermission',
5 permission_name => '*',
6 permission_action => 'read,write'
7 );
8 end;
9 /
PL/SQL procedure successfully completed.
SQL> commit;
Commit complete.
SQL>
Then I connect ESIMSCO_UTIL_OWNER.
connect to ESIMSCO_UTIL_OWNER
Create 2 tables.
create table attachment(
at_file varchar2(500),
at_mimetype varchar2(500),
at_attachment blob
create table email (
em_incident integer,
em_from varchar2(1000),
em_subject varchar2(1000),
em_body nclob
Then Create java source named receivemail.
create or replace and compile java source named receivemail as
import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.io.*;
import java.sql.*;
import sqlj.runtime.*;
import oracle.sql.BLOB;
public class ReceiveMail
static void getAttachments(Message message, int incidentNo)
throws MessagingException, IOException, SQLException {
//String attachments = "";
Object content = message.getContent();
if (content instanceof Multipart)
// -- Multi part message which may contain attachment
Multipart multipart = (Multipart)message.getContent();
// -- Loop through all parts of the message
for (int i=0, n=multipart.getCount(); i<n; i++) {
Part part = multipart.getBodyPart(i);
String disposition = part.getDisposition();
if ((disposition != null) &&(disposition.equals(Part.ATTACHMENT) || disposition.equals(Part.INLINE))) {
//-- This part is a file attachment
String fileName = incidentNo+"_"+part.getFileName().replace(' ','_');
System.out.println("FILE: " + fileName);
String contentType = part.getContentType();
String mimeType = contentType.substring(0,contentType.indexOf(";"));
System.out.println("FILETYPE: " + mimeType);
InputStream is = part.getInputStream();
// -- To work with a BLOB column you have to insert a record
// -- with an emptly BLOB first.
#sql { insert into attachment(at_file, at_mimetype, at_attachment)
values (:fileName, :mimeType, empty_blob()) };
// -- Retrieve the BLOB
BLOB attachment = null;
#sql { select at_attachment into :attachment
from attachment where at_file = :fileName };
// -- Fill the BLOB
OutputStream os = attachment.getBinaryOutputStream();
int j;
while ((j = is.read()) != -1) {
os.write(j);
is.close();
os.close();
// -- Set the BLOB by updating the record
#sql { update attachment set at_attachment = :attachment
where at_file = :fileName };
static String getPlainTextBody(Message message)
throws MessagingException, IOException
Object content = message.getContent();
if (message.isMimeType("text/plain")) {
// -- Message has plain text body only
System.out.println("SIMPLE TEXT");
return (String) content;
} else if (message.isMimeType("multipart/*")) {
// -- Message is multipart. Loop through the message parts to retrieve
// -- the body.
Multipart mp = (Multipart) message.getContent();
int numParts = mp.getCount();
System.out.println("MULTIPART: "+numParts);
for (int i = 0; i < numParts; ++i) {
System.out.println("PART: "+mp.getBodyPart(i).getContentType());
if (mp.getBodyPart(i).isMimeType("text/plain")) {
// -- Return the plain text body
return (String) mp.getBodyPart(i).getContent();
} else if (mp.getBodyPart(i).isMimeType("multipart/*")) {
// -- Body is also multipart (both plain text and html).
// -- Loop through the body parts to retrieve plain text part.
MimeMultipart mmp = (MimeMultipart) mp.getBodyPart(i).getContent();
int numBodyParts = mmp.getCount();
System.out.println("MULTIBODYPART: "+numBodyParts);
for (int j = 0; j < numBodyParts; ++j) {
System.out.println("BODYPART: "+mmp.getBodyPart(j).getContentType());
if (mmp.getBodyPart(j).isMimeType("text/plain")) {
// -- Return the plain text body
return (String) mmp.getBodyPart(j).getContent();
return "";
} else {
System.out.println("UNKNOWN: "+message.getContentType());
return "";
static void saveMessage(Message message)
throws MessagingException, IOException, SQLException
//String body = "";
int incidentNo;
// -- Get a new incident number
#sql { select seq_incident.nextval into :incidentNo from dual };
// -- Get the header information
String from = ((InternetAddress)message.getFrom()[0]).getAddress();
System.out.println("FROM: "+ from);
String subject = message.getSubject();
System.out.println("SUBJECT: "+subject);
// -- Retrieve the plain text body
String body = getPlainTextBody(message);
// -- Store the message in the email table
#sql { insert into email (em_incident, em_from, em_subject, em_body)
values (:incidentNo, :from, :subject, :body) };
// -- Retrieve the attachments
getAttachments(message, incidentNo);
#sql { commit };
// -- Mark message for deletion
// message.setFlag(Flags.Flag.DELETED, true);
public static String Receive(String POP3Server, String usr, String pwd)
Store store = null;
Folder folder = null;
try
// -- Get hold of the default session --
Properties props = System.getProperties();
props.put("mail.pop3.connectiontimeout", "60000");
Session session = Session.getDefaultInstance(props, null);
// -- Get hold of a POP3 message store, and connect to it --
store = session.getStore("pop3");
store.connect(POP3Server,995, usr, pwd);
System.out.println("Connected");
// -- Try to get hold of the default folder --
folder = store.getDefaultFolder();
if (folder == null) throw new Exception("No default folder");
// -- ...and its INBOX --
folder = folder.getFolder("INBOX");
if (folder == null) throw new Exception("No POP3 INBOX");
// -- Open the folder for read_write (to be able to delete message) --
folder.open(Folder.READ_WRITE);
// -- Get the message wrappers and process them --
Message[] msgs = folder.getMessages();
for (int msgNum = 0; msgNum < msgs.length; msgNum++){
saveMessage(msgs[msgNum]);
System.out.println("No more messages");
return ("SUCCESS");
catch (Exception ex){
ex.printStackTrace();
return ex.toString();
finally{
// -- Close down nicely --
try{
// close(true), to expunge deleted messages
if (folder!=null) folder.close(true);
if (store!=null) store.close();
catch (Exception ex){
//ex.printStackTrace();
return ex.toString();
Then create function receivemail.
create or replace function receivemail(pop3_server in string,
pop3_usr in string,
pop3_pwd in string)
return varchar2
is language java name
'ReceiveMail.Receive(java.lang.String,
java.lang.String,
java.lang.String) return String';
And then trying to execute function receivemail, but I am getting following error.
SQL> set serveroutput on
SQL>
SQL> Declare
2 v_error_msg varchar2(10000);
3 Begin
4 v_error_msg:=receivemail('pop3.live.com', '<Hotmail email address>@hotmail.com', 'Hotmail password');
5 dbms_output.put_line(v_error_msg);
6 End;
7 /
javax.mail.AuthenticationFailedException: EOF on socket
PL/SQL procedure successfully completed.
SQL>
I am requesting, please help me to solve this problem.
I will be very thankful for your kind help and support.
Amol......
Edited by: Amol Karyakarte on 31-May-2012 7:27 AMHello,
I don't think this is the right forum, as this question seems to have nothing to do with the Oracle Forms tool.
You'd better ask it in the database forum.
Francois
Maybe you are looking for
-
Hello all, has anyone gotten arch to work on an hp 1030nr netbook? im having issues with the xorg and tried everthing i could find in the wiki and as well as other distro's forums to find solutions.. ive been using arch for over a year now and ive
-
I have a new Mac Mini (2013) and older external hard drive (Lacie) and cd reader/burner (EzQuest). Both have the original Firewire ports and the Mini has the new kind. I bought a cable with both kinds of ends but I plug them in and they don't show
-
GRR2- 4FM-RepPaint(put ABAP code for convert data in field)
Hi, If somebody know how possible add ABAP code for convert data in some column-field of report (by RepWriter,UserExit,BADI)? Thanks a lot.
-
Change language in smartform layout
HI all, I want to change the language of text in smartform. 4 it i go to SE-63 and Translation->Long texts-->smartforms. But the problem is that in target language thre is no hindi language. and also none of these available languages is changable. po
-
Dear Friends I working on shift planning (TCODE PP61) where i choosed profile SAP_000001 (i.e. Org Unit) , i am getting list of pernrs in the org unit irrespective of there time status being maintained as 0 (NO time Evaluation) infotype 0007 Field ZT