MailUtil.java
package mailtest;
import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailUtil {
private String SMTP_HOST = "smtp.gmail.com";
private String FROM_ADDRESS = "yourname@gmail.com";
private String PASSWORD = "yourpassword";
private String FROM_NAME = "Sameera";
public boolean sendMail(String[] recipients, String[] bccRecipients, String subject, String message) {
try {
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "false");
props.put("mail.smtp.ssl.enable", "true");
Session session = Session.getInstance(props, new SocialAuth());
Message msg = new MimeMessage(session);
InternetAddress from = new InternetAddress(FROM_ADDRESS, FROM_NAME);
msg.setFrom(from);
InternetAddress[] toAddresses = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
toAddresses[i] = new InternetAddress(recipients[i]);
}
msg.setRecipients(Message.RecipientType.TO, toAddresses);
InternetAddress[] bccAddresses = new InternetAddress[bccRecipients.length];
for (int j = 0; j < bccRecipients.length; j++) {
bccAddresses[j] = new InternetAddress(bccRecipients[j]);
}
msg.setRecipients(Message.RecipientType.BCC, bccAddresses);
msg.setSubject(subject);
msg.setContent(message, "text/plain");
Transport.send(msg);
return true;
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null, ex);
return false;
} catch (MessagingException ex) {
Logger.getLogger(MailUtil.class.getName()).log(Level.SEVERE, null, ex);
return false;
}
}
class SocialAuth extends Authenticator {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(FROM_ADDRESS, PASSWORD);
}
}
}
Main.java
package mailtest;
public class Main {
public static void main(String[] args) {
String[] recipients = new String[]{"youremail@yahoo.com"};
String[] bccRecipients = new String[]{"youremail@gmail.com"};
String subject = "Hi this is test Mail";
String messageBody = "Test Mail from codesstore.blogspot.com";
new MailUtil().sendMail(recipients, bccRecipients, subject, messageBody);
}
}
Note: mail.jar is required.Can add multiple recipients and BCC recipients
String[] recipients = new String[]{"youremail@yahoo.com","youremail2@yahoo.com"};
Instead of msg.setContent(message, "text/plain") you can use msg.setContent(message, "text/html") then you can add html tags to message body.
Hello...!!! Your Code is very helpful....but i am getting this exception while running it on my machine......
ReplyDeleteCan you help me sort this out....
what is your exception ??
DeleteHi sameera.... How to run this code??
ReplyDeleteHow to solve the javax.mail.SendFailedException: Sending failed; nested exception is: class javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection timed out: connect..
ReplyDeleteNow am having this exception
This is the code for sending emails using Gmail SMTP settings.You have to use your gmail account details for following variables.
Deleteprivate String FROM_ADDRESS = "yourname@gmail.com";
private String PASSWORD = "yourpassword";
I think you have used localhost as SMTP_HOST.That's why code didn't work.
Hi
ReplyDeletei got this problem
javax.mail.MessagingException: Unknown SMTP host: smtp.gmail.com;
how to fix this.
Check weather your internet connection is working properly, proxy or firewall not blocked gmail.
DeleteCheck whether variables and properties are set correctly.
great i found it is working.........thanks a lot man.........
ReplyDeleteHi Sameera; Thanks for uploading the Email code,
ReplyDeleteI need your help in this code..... I got error when i run this code.
Oct 24, 2012 12:34:53 PM main.MailUtil sendMail
SEVERE: null
javax.mail.SendFailedException: Sending failed;
nested exception is:
javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command first. gm7sm3389594wib.10
at javax.mail.Transport.send0(Transport.java:219)
at javax.mail.Transport.send(Transport.java:81)
at main.MailUtil.sendMail(MainUtil.java:56)
at main.Main.main(Main.java:17)
Thanks alot.
Hi while i m using this code i m getting following Error.... please help me to clear this
ReplyDeleteERROR:
com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. qj6sm3608658pbb.69
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:1388)
at com.sun.mail.smtp.SMTPTransport.mailFrom(SMTPTransport.java:959)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:583)
at javax.mail.Transport.send0(Transport.java:169)
at javax.mail.Transport.send(Transport.java:98)
at nvnr.MailUtil.sendMail(MailUtil.java:60)
at nvnr.Main.main(Main.java:19)
That code works fine for me.
DeleteDid you set the following property to 'true'
props.put("mail.smtp.ssl.enable", "true");
yes I set the property to "true".
Deleteim using jsp with tomcat server..where should i add these java files and compile them.i want to send mail through jsp.
ReplyDeleteYou can import MailUtil.java to your jsp and add the mail sending code which is in main method to your jsp.
Deleteadd mail.jar to your libs.
You only use JSPs? Don't you use Servlets. It is a bad practice.
If you use servlets you can import MailUtil.java to your servlet.
i pinged smtp.gmail.com the reply was " Ping request could not find host smtp.gmail.com ". Please check the name and try a
Deletegain.
may be your proxy blocked smtp.gmail.com
DeleteHow can i send an attachment with mail??????????
ReplyDelete1)Change method and add file array
Deletepublic boolean sendMail(String[] recipients, String[] bccRecipients, String subject, String message, String files[]) {
2)
Remove Line 51 msg.setContent(message, "text/plain"); and add this code
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/plain");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
for (int k = 0; k < files.length; k++) {
String filename = files[k];
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filename);
attachmentBodyPart.setDataHandler(new DataHandler(source));
attachmentBodyPart.setFileName(filename);
multipart.addBodyPart(attachmentBodyPart);
}
msg.setContent(multipart);
3) add attachment to Main.java line 10
String[] files={"C:/Users/home/Pictures/testimage.jpg"};
new MailUtil().sendMail(recipients, bccRecipients, subject, messageBody,files);
Getting below error while running above code. Please help
ReplyDeletejavax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
nested exception is:
this code work fine with glassfish server.
ReplyDeleteI use your code and on server i have error Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect
ReplyDeletemy props is good:
m_properties = new Properties();
m_properties.put("mail.smtp.host", "smtp.gmail.com");
m_properties.put("mail.smtp.socketFactory.port", "465");
m_properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
m_properties.put("mail.smtp.auth", "true");
m_properties.put("mail.smtp.port", "465");
m_properties.put("mail.debug", "false");
m_properties.put("mail.smtp.ssl.enable", "true");
and i couldn't figure out cause of this error..
Hi Sameera,
ReplyDeleteI want to use the SMTP service which is running in the server(localhost) instead of a gmail account from the application. Help me..
Maha
how to get rid of following error:
ReplyDeletejavax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 465; nested exception is: java.net.ConnectException: Connection refused: connect
I think you have used localhost as SMTP_HOST.. use smtp.gmail.com
DeleteMar 23, 2013 6:15:18 AM MailUtil sendMail
ReplyDeleteSEVERE: null
javax.mail.SendFailedException: Sending failed;
nested exception is:
javax.mail.MessagingException: 530 5.7.0 Must issue a STARTTLS command f
irst. jk1sm1263378pbb.14 - gsmtp
at javax.mail.Transport.send0(Transport.java:219)
at javax.mail.Transport.send(Transport.java:81)
at MailUtil.sendMail(Send.java:51)
at Send.main(Send.java:83)
when i use above your code at that time got this exception how can i solve this exception pls help me thanks a lot
ReplyDeletehi please give me a code to upload an image into database with text fields
ReplyDeleteplease...
please help sameera..
thanks in advance
Hi tried running this code i got this exception nested exception is:
ReplyDeletejavax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
nested exception is:
I dont know how to include/exclude my proxy settings...