Problem in sending messages using java mail api
Hi All,
I have a problem in sending messages via java mail api.
MimeMessage message = new MimeMessage(session);
String bodyContent = "ñSunJava";
message.setText (bodyContent,"utf-8");using the above code its not possible for me to send the attachment. if i am using the below code means special characters like ñ gets removed or changed into some other characters.
MimeBodyPart messagePart = new MimeBodyPart();
messagePart.setText(bodyText);
// Set the email attachment file
MimeBodyPart attachmentPart = new MimeBodyPart();
FileDataSource fileDataSource = new FileDataSource("C:/sunjava.txt") {
public String getContentType() {
return "application/octet-stream";
attachmentPart.setDataHandler(new DataHandler(fileDataSource));
attachmentPart.setFileName(filename);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messagePart);
multipart.addBodyPart(attachmentPart);
message.setContent(multipart);
Transport.send(message);is there any way to send the file attachment with the body message without using MultiPart java class.
Taken pretty much straight out of the Javamail examples the following works for me (mail read using Thunderbird) // Define message
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
// Set the 'to' address
for (int i = 0; i < to.length; i++)
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set the 'cc' address
for (int i = 0; i < cc.length; i++)
message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i]));
// Set the 'bcc' address
for (int i = 0; i < bcc.length; i++)
message.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[i]));
message.setSubject("JavaMail With Attachment");
// Create the message part
BodyPart messageBodyPart = new MimeBodyPart();
// Fill the message
messageBodyPart.setText("Here's the file ñSunJava");
// Create a Multipart
Multipart multipart = new MimeMultipart();
// Add part one
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
for (int count = 0; count < 5; count++)
String filename = "hello" + count + ".txt";
String fileContent = " ñSunJava - Now is the time for all good men to come to the aid of the party " + count + " \n";
// Create another body part
BodyPart attachementBodyPart = new MimeBodyPart();
// Get the attachment
DataSource source = new StringDataSource(fileContent, filename);
// Set the data handler to this attachment
attachementBodyPart.setDataHandler(new DataHandler(source));
// Set the filename
attachementBodyPart.setFileName(filename);
// Add this part
multipart.addBodyPart(attachementBodyPart);
// Put parts in message
message.setContent(multipart);
// Send the message
Transport.send(message);
Similar Messages
-
Problem in retrieving email using java mail api
hi,
In my project,i am retrieving mails from a particular email id.
I am able to retrieve the latest mails and save it in a folder in my system.
The problem is whenever i run the program eventhough the most recently received mail in inbox is retrieved and saved,again it is retrieving the same one and saving it in the same folder(not repeating).
I tried to check the newmessages in the inbox using the folder.hasNewMessage() method in java mail api,but the method is returning false only regardless new mail is there in inbox or not.
I want to read the unread messages only.Dont want to retrieve the already read mails.
I got the mail retrieving code from the below site.(sorry not posting the code because it is so long and having 4 classes)
http://www.builderau.com.au/program/java/soa/Getting_the_mail_in_receiving_in_JavaMail/0,39024620,39228060,00.htm
Can anyone tell me how to read unread mails in the inbox?
Thanks a lothi parvathi
i think your mail program is receving mails using imap
the imap is only receve the mail from server but the pop is deleting the mails after receving
use the following sample code
package com.sfrc.mail.pop;
import javax.mail.*;
import javax.mail.internet.*;
import com.sun.mail.handlers.message_rfc822;
import java.util.*;
import java.io.*;
* Owner: SFRC IT Solutions Pvt Ltd
* Author:Arunkumar Subramaniam
* Date :12-06-2006
* File Name: AttachRecive.java
public class AttachRecive
public static void main(String args[])
try
String popServer="192.168.1.1";
String popUser="pl";
String popPassword="password";
// Create empty properties
Properties props = new Properties();
// Get session
Session session = Session.getDefaultInstance(props, null);
// Get the store
Store store = session.getStore("pop3");
store.connect(popServer, popUser, popPassword);
// Get folder
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
// Get directory
Message message =folder.getMessages();
Multipart mp = (Multipart)message.getContent();
for (int i=0, n=mp.getCount(); i<n; i++) {
Part part = mp.getBodyPart(i);
String disposition = part.getDisposition();
// Close connection
folder.close(false);
store.close();
catch (Exception ex)
System.out.println("Usage: "
+" popServer popUser popPassword");
System.exit(0);
Regards
Arunkumar Subramaniam
SFRC IT Solutions Pvt Ltd
Chennai -
Problem using Java Mail API with WLS 7.0
Hi All,
I am trying to use the Java Mail API provided by WLS 7.0. I have made the
settings metioned in the WLS 7.0 docs. However when I try to run the program I
am getting the following error:
javax.naming.NoInitialContextException: Need to specify class name in environment
or system property, or as an applet parameter, or in an application resource file:
java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:6
46)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:246
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.jav
a:283)
at javax.naming.InitialContext.lookup(InitialContext.java:350)
The code that I have written is as follows
import java.util.*;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.naming.*;
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
public class MailTo {
public static void main(String args[])
try
//Context ic = getInitialContext();
InitialContext ic = new InitialContext();
/* My jndi name is "testSession" */
Session session = (Session) ic.lookup("testSession"); /* THE PROBLEM IS SHOWN
IN THIS LINE */
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "XX.XX.XX.XX");
/* For security reasons I have written the ip add in this format */
props.put("mail.from", "[email protected]"); /* for security reasons i have
changed the mail address */
Session session2 = session.getInstance(props);
Message msg = new MimeMessage(session2);
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]",
false));
msg.setSubject("Test Message");
msg.setSentDate(new Date());
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText("This is a mail sent to you using JAVA Mail API and Weblogic Server");
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
msg.setContent(mp);
Transport.send(msg);
catch(Exception e)
e.printStackTrace();
}//end of main
public static Context getInitialContext()
throws NamingException
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
p.put(Context.PROVIDER_URL, "t3://localhost:7501/testWebApp");
p.put(Context.SECURITY_PRINCIPAL, "weblogic");
p.put(Context.SECURITY_CREDENTIALS, "weblogic");
return new InitialContext(p);
}//end of class
Can anyone please tell me what is the problem. I thought that we cannot directly
do
InitialContext ic = new InitialContext();
So I had written a method getInitialContext() as shown in the above piece of code,
but that too did not work.
Eagerly awaiting a response.
Jimmy ShahYou can use InitialContext ic = new InitialContext() only if you are using a startup class, servlet or a JSP i.e
server side code.
If you are using a java client you need to use Context ic = getInitialContext();
Try this code
import java.util.*;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.naming.*;
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
public class MailTo {
public static void main(String args[])
try {
Properties h = new Properties();
h.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
h.put(Context.PROVIDER_URL, "t3://localhost:7001");
Context ic = new InitialContext(h);
Session session = (Session) ic.lookup("testSession");
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "XX.XX.XX.XX");
props.put("mail.from", "[email protected]");
Session session2 = session.getInstance(props);
Message msg = new MimeMessage(session2);
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse("[email protected]",false));
msg.setSubject("Test Message");
msg.setSentDate(new Date());
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText("This is a mail sent to you using JAVA Mail API and Weblogic Server");
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
msg.setContent(mp);
Transport.send(msg);
catch(Exception e)
e.printStackTrace();
}//end of main
}//end of class
We have shipped a javamail example in the samples\server\src\examples\javamail folder.
Jimmy Shah wrote:
Hi All,
I am trying to use the Java Mail API provided by WLS 7.0. I have made the
settings metioned in the WLS 7.0 docs. However when I try to run the program I
am getting the following error:
javax.naming.NoInitialContextException: Need to specify class name in environment
or system property, or as an applet parameter, or in an application resource file:
java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:6
46)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:246
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.jav
a:283)
at javax.naming.InitialContext.lookup(InitialContext.java:350)
The code that I have written is as follows
import java.util.*;
import javax.activation.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.naming.*;
import java.io.*;
import java.net.InetAddress;
import java.util.Properties;
import java.util.Date;
public class MailTo {
public static void main(String args[])
try
//Context ic = getInitialContext();
InitialContext ic = new InitialContext();
/* My jndi name is "testSession" */
Session session = (Session) ic.lookup("testSession"); /* THE PROBLEM IS SHOWN
IN THIS LINE */
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "XX.XX.XX.XX");
/* For security reasons I have written the ip add in this format */
props.put("mail.from", "[email protected]"); /* for security reasons i have
changed the mail address */
Session session2 = session.getInstance(props);
Message msg = new MimeMessage(session2);
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]",
false));
msg.setSubject("Test Message");
msg.setSentDate(new Date());
MimeBodyPart mbp = new MimeBodyPart();
mbp.setText("This is a mail sent to you using JAVA Mail API and Weblogic Server");
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp);
msg.setContent(mp);
Transport.send(msg);
catch(Exception e)
e.printStackTrace();
}//end of main
public static Context getInitialContext()
throws NamingException
Properties p = new Properties();
p.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
p.put(Context.PROVIDER_URL, "t3://localhost:7501/testWebApp");
p.put(Context.SECURITY_PRINCIPAL, "weblogic");
p.put(Context.SECURITY_CREDENTIALS, "weblogic");
return new InitialContext(p);
}//end of class
Can anyone please tell me what is the problem. I thought that we cannot directly
do
InitialContext ic = new InitialContext();
So I had written a method getInitialContext() as shown in the above piece of code,
but that too did not work.
Eagerly awaiting a response.
Jimmy Shah--
Rajesh Mirchandani
Developer Relations Engineer
BEA Support -
Using Java Mail API from Tomcat
Hello,
Purely as an academic exercise I have written a JSP page which, upon being requested from the client's browser, should send me a default email using Java Mail Api.
here is the code :
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class TestMail {
static String msgText1 = "success this time 12";
static String msgText2 = "This is the text in the message attachment.";
public String sendIt() {
String to = "<my email";
String from = "<anything>";
String host = "<my ip address of smtp server>";
boolean debug = false;
Properties props = new Properties();
props.put("mail.smtp.host", host);
Session session = Session.getInstance(props, null);
.....The code works fine as a stand alone app but when called from JSP page it hangs on the Session.getInstance line. I can only guess that this might be a security issue with the container not allowing access to the smtp server ?
Can anyone give me a clue ???Your Tomcat log files should spell out the problem for you.
My Tomcat installation does not come with the Java Mail API. I had to add the mail and activation jar files to the server/common.lib directory (or the server's shared/lib or the WEB-INF/lib of your application.)
HTH. -
Using Java mail API from JSPDynPage
Hi Experts,
I am working on a Portal Assignment that requiresto sent work flow mails on the basis of error conditions.
Can u please suggest if at all I can use Java Mail APIs from JSP page within the JSP DYN Page Framework.
If at all Java Mail can be used could u please suugest some help docs on the same.
Thanks for the help.
Manab C Ghosh
EP Consultant
Kolkata INDIA
+919830603327Hi Experts,
Thanks for all the responses to my Mail question(mailing from JSPDynPage).
I have found the solution.
Here is how I have got the things: (pls note there are other solns)
Using Java Mail APIs;
Create a Java file in the scr.core / src.api
MailSender.java
* Created on Jul 21, 2005
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
package com.mailsend.test;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
* Edited on Jul 24, 2005
* @author Manab C Ghosh
public class MailSender {
public String sendMessage(){
String msg ="Hello mail Test";
String smtpServer ="mySMTPServer";
String smtpSender = "senderemailaddress";
String smtpRecipient="receipientemailaddress";
String stBody = msg ;
//String stDate = new Date().toString() ;
String stSubject = "Mail Test ";
Send( smtpServer, //SMTPServer
smtpSender, //Sender
smtpRecipient, //Recipient
stSubject, //Subject
stBody //Body
); //Attachments
return "Mail Success";
public static void Send(String SMTPServer,
String From,
String To,
String Subject,
String msgText1
// Error status;
int ErrorStatus = 0;
// create some properties and get the default Session
Properties props = System.getProperties();
props.put("mail.smtp.host", SMTPServer);
Session session = Session.getDefaultInstance(props, null);
try {
// create a message
MimeMessage msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(From));
InternetAddress[] address = {new InternetAddress(To)};
msg.setRecipients(Message.RecipientType.TO, address);
msg.setSubject(Subject);
// create and fill the first message part
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(msgText1);
// create the Multipart and its parts to it
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
//mp.addBodyPart(mbp2);
// add the Multipart to the message
msg.setContent(mp);
// set the Date: header
msg.setSentDate(new Date());
// send the message
Transport.send(msg);
} catch (MessagingException mex) {
Call this file from the JSP page (which is set at JSPDynPage controller)
one important thing-----
Create a dir under PORTAL-INF and import the following jars-- activation.jar, mail.jar,imap.jar,smtp.jar, mailapi.jar.
This works..
Thanks once again to the Experts.
happy mailing
Manab Ghosh.
INDIA (+919830603327) -
How can i access gmail's smtp server using java mail api
i m using java mail api to access gmails pop and smtp service to receive and send mail from ur gmail account. I m able to access gmails pop server using the ssl and port 995 , but i can not use its smtp server to which i m connecting using ssl on 465 port. It requires authentication code.
if anybody can help me in this regard i m thnkful to him/her.
thnks in advance.
jogin desaiHere's an example of using SSL + Authentication
http://onesearch.sun.com/search/onesearch/index.jsp?qt=ssl+authentication&subCat=siteforumid%3Ajava43&site=dev&dftab=siteforumid%3Ajava43&chooseCat=javaall&col=developer-forums -
Using java mail api without servlets, I ve sent an html mail. In that Ive
Using java mail api without servlets, I ve sent an html mail. In that Ive specified action to the servlet. On click, it shows url as file:///C:/Documents%20and%20Settings/sirivanig/Local%20Settings/Temporary%20Internet%20Files/Content.IE5/CNFHMDIT/updatemailerform%5B2%5D.htm instead of www.servername.com/....
May I know the reason why it shows like this.
Do I ve to send htmlmail through servlet so that it does show proper url?Possibly your mailer is restricting your access to URLs to prevent
various scams. Without the details, it's hard to know what's going
wrong.
Have you tried with a different mailer? -
How to do SAVE AS DRAFT using java mail api
Hello,
I want to know how to do SAVE AS DRAFT using Java mail Api.
thanksHello,
I want to know how to do SAVE AS DRAFT using Java
mail Api.
thanksI don't think you can. That sounds like a feature of a mail client app itself. The Java mail API is for when you're ready to actually send the thing. Saving drafts is storing them somewhere like you would any other data; nothing to do with the mail API. -
I have an iMac, and have a Verizon DSL account (3 email addresses). Recently, my Mac Mail keeps requesting the passwords on my accounts every few minutes, and will not allow me to send messages using Mac Mail (the message says that the outgoing server was rejected. I cannot edit the outgoing server, and the keychain will not save my passwords (the ports are valid). How can I change the outgoing server to send emails, and how can I avoid having Mail request my passwords every 2 minutes? Verizon, as usual, will not provide support to iMacs.
Is there an email saved in your drafts or outbox folder? I suspect that Mail is continually trying to send it, and each time Google is rejecting the email message.
You can open the message and then delete it from your Outbox folder. Then try removing all @gmail email addresses from it and seeing whether you can send to the other folks. I suspect that will work.
With email, if an SMTP server *can* verify email addresses, sometimes it will and it will refuse to send messages. If a message has to be relayed across servers, no verification is done, and you'll get a bounce if an email address is bad. -
Can i use java mail APIs to read Unix mail
hi
can i use java mail APIs to read Unix mail?
Unix has "mail" command which can be used to access mails on the Unix system.
is it possible to execute mail & access unix mails remotely using POP/IMAP
thanks in advanceThere are JavaMail providers that allow you to access the Unix mail spool files directly. Alternatively the standard JavaMail API can access a POP or IMAP server, if one is installed.
-
How to use Java Mail API in Unix
I am trying to write some code using Java mail API. I want to execute it in Unix. I downloaded the mail API to windows machine and ftped the mail.jar file to a Unix machine. Then I set the class path as below:
export CLASSPATH=$CLASSPATH:/home.../mail.jar
Then I tried to compile my Java program. The output is as below:
error: error reading /home.../mail.jar; invalid END header (bad central directory offset)
mail.java:1: package javax.mail does not exist
import javax.mail.*;
Can any one please help me out.You should also include the "activation.jar" file that you obtained from
downloading the Java Activation Framework, in your CLASSPATH.
For example:
export CLASSPATH=$CLASSPATH:/urPath/activation/activation.jar
Besides, assuming you unzipped javamail-1_4_1.zip in home/download the following should work
export CLASSPATH=$CLASSPATH:home/download/javamail-1.4.1/mail.jar:. -
Error while sending mail when using Java Mail API
Hi Experts,
I am trying to execute a webdynpro application which uses the Java Mail API to send emails. The exception that I get on executing the application is :
Sending failed; nested exception is: javax.mail.SendFailedException: Invalid Addresses; nested exception is: javax.mail.SendFailedException: 550 5.7.1 Unable to relay for [email protected]
Can anybody please help me sort out the issue.
Regards
AbdullahHi,
Usually one get this error if the SMTP server is configured not to relay mails (a security measure) or the SMTP server need the mail to be sent from a trusted IP or with proper authentication. Some SMTP servers are configured to block junk mails.
Pls check with your mail server administrator.
Regards -
Java.lang.UnsupportedClassVersionError while using java mail api
Hi Everybody ,
I am new comer to this forum , and would like to be an active member.
I am getting this error while trying to use the java mail api to send an email using smtp.
The error is as follows :
Exception in thread "main" java.lang.UnsupportedClassVersionError: javax/mail/Message (Unsupported major.minor version 48.0)
Can Anyone please tell where I am wrong.
I am using the following code
==============================================================
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.abc.com");
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props, null);
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);
// Optional : You can also set your custom headers in the Email if you Want
msg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
==============================================================Hi Philip ,
Thanks for the prompt reply , I had installed oracle client services which overid my jdk1.4 installation with jdk1.3 and hence the error. I changed my classpath settings to point to jdk1.4 and it owrked properly.
Thanks once again.
regards,
Rupesh Rajan -
Save Attachment from exchange server 2010 from oracle using java mail API
Hello,
I want to read email from microsoft exchangeserver 2010 and save attachement into a folder.I created an Java program to import attachments from a exchange server mailbox using "POP3S".It works fine when run as a java application.But when i put this inside Oracle11g R2 using load java and while executing from a procedure it gives an error at parsing message into Multipart
Error at line : Multipart mp = (Multipart)m.getContent();
Error:
Content-Type: multipart/mixed;
boundary="_002_A0C2E09A..................................."
java.lang.ClassCastException
at mailPop3.checkmail(mailPop3:71)
My Java Class is as follows,
import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Date;
The function i used to check for attachments is given below.
public static boolean hasAttachments(Message m) throws java.io.IOException, MessagingException
Boolean hasAttachments = false;
try
// if it is a plain/html text - no attachements
if (m.isMimeType("text/*"))
return hasAttachments;
else if (m.isMimeType("multipart/alternative"))
return hasAttachments;
else if (m.isMimeType("multipart/*"))
Multipart mp = (Multipart)m.getContent();
if (mp.getCount() > 1)
hasAttachments = true;
return hasAttachments;
catch (Exception e) {
e.printStackTrace();
} finally {
return hasAttachments;
My Java Details as follows
java Version :1.5.0_10
java.vm.specification.version:1.0
java.vm.version :1.5.0_01
java.specification.version:1.5
java.class.version:48.0
Java mail API:javamail-1.4.4
Used Jars:mail.jar
Could someone explain why I am getting this error? What can I do to resolve this error?
Is any other Jar need other than mail.jar?
Any help would be much appreciated.
Regards,
NisanthHai EJP,
Thanks for your reply,
My full java class as follows,
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Part;
import javax.mail.Multipart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeMessage;
public class Newmail
public Newmail()
super();
public static int mailPOP3(String phost,
String pusername,
String ppassword)
Folder inbox =null;
Store store =null;
int result = 1;
try
String host=phost;
final String username=pusername;
final String password=ppassword;
System.out.println("Authenticator");
Authenticator auth=new Authenticator()
protected PasswordAuthentication getPasswordAuthentication()
return new PasswordAuthentication(username, password);
System.out.println("Certificate");
String filename="D:\\Certi\\jssecacerts";
String password2 = "changeit";
System.setProperty("javax.net.ssl.trustStore",filename);
System.setProperty("javax.net.ssl.trustStorePassword",password2);
Properties props = System.getProperties();
System.out.println("host-----"+props);
props.setProperty("mail.pop3s.port", "993");
props.setProperty("mail.pop3s.starttls.enable","true");
props.setProperty("mail.pop3s.ssl.trust", "*");
Session session = Session.getInstance(props,auth);
session.setDebug(true);
store = session.getStore("pop3s");
System.out.println("store------"+store);
store.connect(host,username,password);
System.out.println("Connected...");
inbox = store.getDefaultFolder().getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message[] msgs = inbox.getMessages();
System.out.println("msgs.length-----"+msgs.length);
result = 0;
int no_of_messages = msgs.length;
for ( int i=0; i < no_of_messages; i++)
System.out.println("msgs.count-----"+i);
System.out.println("Attachment....>"+msgs.getContentType());
Multipart mp = (Multipart)msgs[i].getContent();
System.out.println("Casting Success" + mp.getContentType());
catch(Exception e)
e.printStackTrace();
finally
try
if(inbox!=null)
inbox.close(false);
if(store!=null)
store.close();
return result;
catch(Exception e)
e.printStackTrace();
return result;
Please check it
Regards,
Nisanth -
Problem in sending mail using java mail api
This is the pogram I am using as of now to send a mail to yahoo id.
import javax.mail.*;
import javax.mail.internet.*;
public class SendingMail2
public SendingMail2()
try
String from = "ravikiran_sunrays";
String to = "[email protected]";
String subject = "the subject u wanna send ";
String cc="[email protected]";
String bcc="[email protected]";
String text="the matter that u wanna send ";
java.util.Properties prop = System.getProperties();
prop.put("mail.smtp.host","mail.yahoo.com");
//prop.put("http.proxyHost",System.getProperty("http.proxyHost"));
//prop.put("http.proxyPort","8080");
//prop.put("http.proxyPort",System.getProperty("http.proxyPort"));
//prop.put("http.proxyHost","172.19.48.201");
//System.getProperties().setProperty("http.proxyPort","8080");
//System.getProperties().setProperty("http.proxyHost","172.19.48.201");
Session ses = Session.getInstance(prop,null);
MimeMessage message = new MimeMessage(ses);
try
Address fromAddress = new InternetAddress(from);
message.setFrom(fromAddress);
message.setSubject(subject);
Address[] toAddress = InternetAddress.parse(to);
Address[] cc_address=InternetAddress.parse(cc);
Address[] bcc_address=InternetAddress.parse(bcc);
message.setRecipients(Message.RecipientType.TO,toAddress);
message.setRecipients(Message.RecipientType.CC,cc_address);
message.setRecipients(Message.RecipientType.BCC,bcc_address);
message.setSentDate(new java.util.Date());
message.setText(text);
Transport.send(message);
System.out.println("Mail Successfully Sent");
catch(Exception e)
System.out.println("Problem " + e);
catch(Exception e)
System.out.println("Problem " + e);
public static void main(String[] args)
SendingMail2 sendingMail2 = new SendingMail2();
This is the exception I am getting when I try 2 execute that program.
avax.mail.SendFailedException: Sending failed;
nested exception is:
javax.mail.MessagingException: Unknown SMTP host: mail.yahoo.com;
nested exception is:
java.net.UnknownHostException: mail.yahoo.comlisten buddy
this is a class i made it is easy to understand it sends mails and check inbox just adduser from telnet with remote manager in james create the three accounts i am using and then use this class and its methods
also the next class that contains the mails test my class and what i am saying
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class MailClient
extends Authenticator
public static final int SHOW_MESSAGES = 1;
public static final int CLEAR_MESSAGES = 2;
public static final int SHOW_AND_CLEAR =
SHOW_MESSAGES + CLEAR_MESSAGES;
protected String from;
protected Session session;
protected PasswordAuthentication authentication;
public MailClient(String user, String host)
this(user, host, false);
public MailClient(String user, String host, boolean debug)
from = user + '@' + host;
authentication = new PasswordAuthentication(user, user);
Properties props = new Properties();
props.put("mail.user", user);
props.put("mail.host", host);
props.put("mail.debug", debug ? "true" : "false");
props.put("mail.store.protocol", "pop3");
props.put("mail.transport.protocol", "smtp");
session = Session.getInstance(props, this);
public PasswordAuthentication getPasswordAuthentication()
return authentication;
public void sendMessage(
String to, String subject, String content)
throws MessagingException
System.out.println("SENDING message from " + from + " to " + to);
System.out.println();
MimeMessage msg = new MimeMessage(session);
msg.addRecipients(Message.RecipientType.TO, to);
msg.setSubject(subject);
msg.setText(content);
Transport.send(msg);
public void checkInbox(int mode)
throws MessagingException, IOException
if (mode == 0) return;
boolean show = (mode & SHOW_MESSAGES) > 0;
boolean clear = (mode & CLEAR_MESSAGES) > 0;
String action =
(show ? "Show" : "") +
(show && clear ? " and " : "") +
(clear ? "Clear" : "");
System.out.println(action + " INBOX for " + from);
Store store = session.getStore();
store.connect();
Folder root = store.getDefaultFolder();
Folder inbox = root.getFolder("inbox");
inbox.open(Folder.READ_WRITE);
Message[] msgs = inbox.getMessages();
if (msgs.length == 0 && show)
System.out.println("No messages in inbox");
for (int i = 0; i < msgs.length; i++)
MimeMessage msg = (MimeMessage)msgs;
if (show)
System.out.println(" From: " + msg.getFrom()[0]);
System.out.println(" Subject: " + msg.getSubject());
System.out.println(" Content: " + msg.getContent());
if (clear)
msg.setFlag(Flags.Flag.DELETED, true);
inbox.close(true);
store.close();
System.out.println();
====================================
testing this class
=======================================
public class JamesConfigTest
public static void main(String[] args)
throws Exception
// CREATE CLIENT INSTANCES
MailClient redClient = new MailClient("red", "localhost");
MailClient greenClient = new MailClient("green", "localhost");
MailClient blueClient = new MailClient("blue", "localhost");
// CLEAR EVERYBODY'S INBOX
redClient.checkInbox(MailClient.CLEAR_MESSAGES);
greenClient.checkInbox(MailClient.CLEAR_MESSAGES);
blueClient.checkInbox(MailClient.CLEAR_MESSAGES);
Thread.sleep(500); // Let the server catch up
// SEND A COUPLE OF MESSAGES TO BLUE (FROM RED AND GREEN)
redClient.sendMessage(
"blue@localhost",
"Testing blue from red",
"This is a test message");
greenClient.sendMessage(
"blue@localhost",
"Testing blue from green",
"This is a test message");
Thread.sleep(500); // Let the server catch up
// LIST MESSAGES FOR BLUE (EXPECT MESSAGES FROM RED AND GREEN)
blueClient.checkInbox(MailClient.SHOW_AND_CLEAR);
=======================================================
it suppose to print this
Clear INBOX for red@localhost
Clear INBOX for green@localhost
Clear INBOX for blue@localhost
SENDING message from red@localhost to blue@localhost
SENDING message from green@localhost to blue@localhost
Show and Clear INBOX for blue@localhost
From: green@localhost
Subject: Testing blue from green
Content: This is a test message
From: red@localhost
Subject: Testing blue from red
Content: This is a test message
thanks a lot
but i need ur help plzzzzzzzzzzzz
i can create account from telnet
but how i can create a new account from java .. a jsp page that i made to create a new account on the server
plzzzzzzzz help me
bye
Maybe you are looking for
-
11.1.4.62 itunes update not recognizing ipod touch
Please Help. Did the update to Windows 8.1 yesterday and now iTunes does not recognize my iPod(s) etc. I looked in Windows and device shows up but now in iTunes. I downloaded the new iTunes and reinstalled (Repair) and that did not help. Anyone h
-
Using OD as a simple contact list for mail
Hello, A probably stupid question but ... : is it possible to add, in Open Directory, informations like e-mail or mobile phone number WITHOUT creating an account in Open Directory ? This is what i'm trying to do : we have an OS X server with Open Dir
-
Contract History Table - To track the POs for the Contract
Hi Experts, I would like to prepare a report to track the Contracts (the history of the contracts - Purchase Orders (PO) for range of Contracts). Example: I required to display in columns - Contract Number, Contarct Dates, PO Numbers. So, Pleaes let
-
Possible to turn off single-click in Bookmark sidebar?
I appreciate the bookmark sidebar, but I really wish that I could select something in it without automatically loading that location in the browser. Is there a user_pref or some other way to make the bookmark sidebar items only load on a double-click
-
hi guru's i did't find client system under Admin in MDM console repository. in the process of r/3 integration with mdm through xi. Thanks in advance Swari