Monday, May 14, 2012

Send Email in Java Mail API using Gmail SMTP Server

To send email using java you must have mail server and user name and password to access the mail server. In this tutorial I used gmail SMTP server with SSL connection. You must add Java Mail API to your class path.

package jsupport.mail;

import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
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;

 * @author Java Srilankan Support - JSupport
public class SendMail {
    public void sendMail(String m_from,String m_to,String m_subject,String m_body){

      try {

            m_properties     = new Properties();
            m_properties.put("", ""); 
            m_properties.put("mail.smtp.socketFactory.port", "465");
            m_properties.put("mail.smtp.auth", "true");
            m_properties.put("mail.smtp.port", "465");

            m_Session        =   Session.getDefaultInstance(m_properties,new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("username","password"); // username and the password

            m_simpleMessage  =   new MimeMessage(m_Session);

            m_fromAddress    =   new InternetAddress(m_from);
            m_toAddress      =   new InternetAddress(m_to);

            m_simpleMessage.setRecipient(RecipientType.TO, m_toAddress);


        } catch (MessagingException ex) {

    public static void main(String[] args) {

      SendMail send_mail    =   new SendMail();
      send_mail.sendMail("", "", "Test Mail", "Hi this is Test mail from Java Srilankan Support");

    private Session m_Session;
    private Message m_simpleMessage;
    private InternetAddress m_fromAddress;
    private InternetAddress m_toAddress;
    private Properties m_properties;


Ádám Szikra said...

Thanks, its worked!

Stefan Neureiter said...
This comment has been removed by the author.
sarabjeet said...

i really like that you are giving information on core and advance java concepts. Being enrolled at i found your information very helpful indeed.thanks for it.

Henry Thai said...

Thanks for all! It's worked!

Ádám Szikra said...

How can I integrate to/in JavaApplet?

vmksuw said...

Thank You...working fine

biswjait samal said...

It worked... many many thanks

Post a Comment