Wednesday, 6 April 2016

How to send e-mail from a simple java program ?


Use Mail API

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMail {
    private String from;
    private String to;
    private String subject;
    private String text;

    public SendMail( String from, String to,String subject,
                     String text) {
        this.from = from;
        this.to = to;
        this.subject = subject;
        this.text = text;
    }
    
    void send() {
        Properties props = new Properties();
        // start tls true
        props.put("mail.smtp.starttls.enable", "true"); 
        // set host of mail server to whoom we are sending mail
        props.put("mail.smtp.host", "smtp.gmail.com");  
        // Set the mail server port
        props.put("mail.smtp.port", "465");  
        
        Session mailSession = Session.getDefaultInstance(props);
        Message simpleMessage = new MimeMessage(mailSession);
        
        InternetAddress fromAddress = null;
        InternetAddress toAddress = null;
        
        try {
            fromAddress = new InternetAddress(from);
            toAddress = new InternetAddress(to);
        } catch (AddressException e) {
            e.printStackTrace();
        }
        
        try {
            simpleMessage.setFrom(fromAddress);
            simpleMessage.setRecipient(Message.RecipientType.TO, toAddress);
            simpleMessage.setSubject(subject);
            simpleMessage.setText(text);
            Transport.send(simpleMessage);
            System.out.println("Mail sent successully ");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

public class SendMailTest {
    /**
     * @param args
     */
    public static void main(String[] args) {
        String from = "xyz@gmail.com";
        String to = "abc@gmail.com";
        String subject = "Test";
        String message = "Test message from java program";
        
        SendMail sendMail = new SendMail(from, to, subject, message);
        sendMail.send();
    }
}

No comments:

Post a Comment

Note: only a member of this blog may post a comment.