Java J2ME JSP J2EE Servlet Android

Sending email using SSL connection : Java

This is a demo class to send email using SSL connection with email server..



import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;

import java.util.Date;
import java.util.Properties;


public class SimpleSSLMail {

private static final String SMTP_HOST_NAME = "smtp.gmail.com";
private static final int SMTP_HOST_PORT = 465;
private static final String SMTP_AUTH_USER = "abc@gmail.com";
private static final String SMTP_AUTH_PWD = "1234567";

public static void main(String[] args) throws Exception{
new SimpleSSLMail().test();
}

public void test() throws Exception{
Properties props = new Properties();

props.put("mail.transport.protocol", "smtps");
props.put("mail.smtps.host", SMTP_HOST_NAME);
props.put("mail.smtps.auth", "true");
// props.put("mail.smtps.quitwait", "false");

Session mailSession = Session.getDefaultInstance(props);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();

MimeMessage message = new MimeMessage(mailSession);
message.setSubject("Testing SMTP-SSL");
message.setContent("This is a test", "text/plain");

message.setFrom(new InternetAddress("sharifhome@smile.com.bd"));
message = attachment(message,"This is a test", "D:\\user.txt");
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("sharifruet@smile.com.bd"));

transport.connect
(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);

transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
}
MimeMessage attachment(MimeMessage msg, String text, String file) throws MessagingException{
MimeBodyPart mbp1 = new MimeBodyPart();
mbp1.setText(text);

// create the second message part
MimeBodyPart mbp2 = new MimeBodyPart();

// attach the file to the message
FileDataSource fds = new FileDataSource(file);
mbp2.setDataHandler(new DataHandler(fds));
mbp2.setFileName(fds.getName());

// create the Multipart and add its parts to it
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
mp.addBodyPart(mbp2);

// add the Multipart to the message
msg.setContent(mp);

// set the Date: header
msg.setSentDate(new Date());
return msg;
}
}