Sending mail from your Java application using google SMTP

Previous few I was trying to send mail from my JSP page. I had tried every way to make that code work. Later I found that I have to set  Mail Authentication, which lead me to solution.
Here is my SendMail cass, which you can implement in any Java application to send mail.

SendMail.java

/**
 *
 * @author Prashant
 */
import java.security.Security;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.PasswordAuthentication;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMail {

	private String to;
	private String subject;
	private String text;

	public SendMail(String to, String subject, String text){
		this.to = to;
		this.subject = subject;
		this.text = text;
	}

	public void send() throws NoSuchProviderException, AddressException{

		try
		{
			Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
			Properties props=new Properties();
			props.setProperty("mail.transport.protocol","smtp");
			props.setProperty("mail.host","smtp.gmail.com");
			props.put("mail.smtp.auth","true");
			props.put("mail.smtp.port","465");
			props.put("mail.debug","true");
			props.put("mail.smtp.socketFactory.port","465");
			props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
			props.put("mail.smtp.socketFactory.fallback","false");
			Session session=Session.getDefaultInstance(props,new GJMailAuthenticator());
			session.setDebug(true);
			Transport transport=session.getTransport();
			InternetAddress addressFrom=new InternetAddress("sender@gmail.com");
			MimeMessage message=new MimeMessage(session);
			message.setSender(addressFrom);
			message.setSubject(subject);
			message.setContent(text,"text/html");
			InternetAddress addressTo=new InternetAddress(to);
			message.setRecipient(Message.RecipientType.TO,addressTo);
			transport.connect();
			Transport.send(message);
			transport.close();
			System.out.println("DONE");

		}
		catch(Exception e)
		{

			e.printStackTrace();
		}
	}
}
class GJMailAuthenticator extends javax.mail.Authenticator{
	protected PasswordAuthentication getPasswordAuthentication()
	{
		return new PasswordAuthentication("sender@gmail.com","sender_password");

	}
}

Mail.java

/**
 *
 * @author Prashant
 */
public class Mail {

	public static void main(String[] args) {

		String to = "yohoprashant@yahoo.com";
		String subject = "Test";
		String message = "A test message";

		SendMail sendMail = new SendMail(to, subject, message);
                try
                {
                    sendMail.send();
                }
                catch (Exception e)
                {
                    //
                }
	}
}

Note:  If you want to use yahoo server instead of google, just you have to change the Port address to 25.

  1. import javax.mail.*;
  2. import javax.mail.internet.*;
  3. import java.util.*;
  4. public class Mail
  5. {
  6. String d_email = “iamdvr@gmail.com”,
  7. d_password = “****”,
  8. d_host = “smtp.gmail.com”,
  9. d_port  = “465”,
  10. m_to = “iamdvr@yahoo.com”,
  11. m_subject = “Testing”,
  12. m_text = “Hey, this is the testing email using smtp.gmail.com.”;
  13. public static void main(String[] args)
  14. {
  15. String[] to={“XXX@yahoo.com”};
  16. String[] cc={“XXX@yahoo.com”};
  17. String[] bcc={“XXX@yahoo.com”};
  18. //This is for google
  19. Mail.sendMail(“venkatesh@dfdf.com”,“password”,“smtp.gmail.com”,“465”,“true”,
  20. “true”,true,“javax.net.ssl.SSLSocketFactory”,“false”,to,cc,bcc,
  21. “hi baba don’t send virus mails..”,“This is my style…of reply..
  22. If u send virus mails..”);
  23. }
  24. public synchronized static boolean sendMail(String userName,String passWord,String host,String port,String starttls,String auth,boolean debug,String socketFactoryClass,String fallback,String[] to,String[] cc,String[] bcc,String subject,String text){
  25. Properties props = new Properties();
  26. //Properties props=System.getProperties();
  27. props.put(“mail.smtp.user”, userName);
  28. props.put(“mail.smtp.host”, host);
  29. if(!“”.equals(port))
  30. props.put(“mail.smtp.port”, port);
  31. if(!“”.equals(starttls))
  32. props.put(“mail.smtp.starttls.enable”,starttls);
  33. props.put(“mail.smtp.auth”, auth);
  34. if(debug){
  35. props.put(“mail.smtp.debug”, “true”);
  36. }else{
  37. props.put(“mail.smtp.debug”, “false”);
  38. }
  39. if(!“”.equals(port))
  40. props.put(“mail.smtp.socketFactory.port”, port);
  41. if(!“”.equals(socketFactoryClass))
  42. props.put(“mail.smtp.socketFactory.class”,socketFactoryClass);
  43. if(!“”.equals(fallback))
  44. props.put(“mail.smtp.socketFactory.fallback”, fallback);
  45. try
  46. {
  47. Session session = Session.getDefaultInstance(props, null);
  48. session.setDebug(debug);
  49. MimeMessage msg = new MimeMessage(session);
  50. msg.setText(text);
  51. msg.setSubject(subject);
  52. msg.setFrom(new InternetAddress(“p_sambasivarao@sutyam.com”));
  53. for(int i=0;i<to.length;i++){
  54. msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i]));
  55. }
  56. for(int i=0;i<cc.length;i++){
  57. msg.addRecipient(Message.RecipientType.CC, new InternetAddress(cc[i]));
  58. }
  59. for(int i=0;i<bcc.length;i++){
  60. msg.addRecipient(Message.RecipientType.BCC, new InternetAddress(bcc[i]));
  61. }
  62. msg.saveChanges();
  63. Transport transport = session.getTransport(“smtp”);
  64. transport.connect(host, userName, passWord);
  65. transport.sendMessage(msg, msg.getAllRecipients());
  66. transport.close();
  67. return true;
  68. }
  69. catch (Exception mex)
  70. {
  71. mex.printStackTrace();
  72. return false;
  73. }
  74. }
  75. }
Advertisements

2 Responses to Sending mail from your Java application using google SMTP

  1. Sorin says:

    Excellent, it works perfectly. I will modify it to attach binary files to messages, it is an excellent starting point. Thank you, Prashant.

  2. me says:

    i nned some help please i got this error “The method setSender(InternetAddress) is undefined for the type MimeMessage” but setSender is defined in MimeMessage i don’t know where is the problem

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: