Friday, January 10, 2014

Send Mail using Java

import java.util.Properties;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class MailTest {
     public static void main(String[] args) throws Exception{
        System.err.println("Sending Email : ");
        sendSMTP("bip@gmail.com", "Hi", "Testing from MailTest");
        System.err.println("Email Send Successfully : ");
    }
    // Set up the mail profile in the static initializer of the class
    private static final Properties props;
    static {
        props = new Properties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.host", "gmail.com");
        props.put("mail.smtp.port", "25");
//      props.put("mail.smtp.port", "587");
        props.put("mail.stmp.user", "bg@gmail.com");
        props.put("mail.smtp.password", "doom3$");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.starttls.required", "true");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.auth.ntlm.domain", "gmail.com");
        props.put("mail.smtp.auth.mechanisms", "LOGIN NTLM");
        props.put("mail.debug", "true");
        props.put("mail.smtp.ssl.trust", "gmail.com");
    }
    public static int sendSMTP(String toAddress, String subject, String content) throws Exception
    {
        InternetAddress from = new InternetAddress("bipin_gupta@syntelinc.com");
        InternetAddress recipient = new InternetAddress(toAddress);
        // Create a Session to send e-mail from static profile
        Session session = Session.getInstance(MailTest.props);
        // Create the message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(from);
        msg.setSubject(subject);
        msg.setText(content);
        msg.addRecipient(Message.RecipientType.TO, recipient);
        msg.saveChanges();
        // Send the message
        Transport transport = session.getTransport(); 
transport.connect(props.get("mail.smtp.host").toString(),props.get("mail.stmp.user").toString(),props.get("mail.smtp.password").toString());
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
        return 0;
    }
}