Saturday 26 January 2013

Send SMTP E-Mail in Java

This post will give you the understanding of very basic Java required to send SMTP e-mail.
You basically need to download (click here) "mail-1.4.jar".
Link the "mail-1.4.jar" file to your library: (See pic below)
Compile the following java code:

import java.util.Properties;
import javax.mail.Message;
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 SUNEET
 */
public class Web {

    /**
     * @param args the command line arguments
     */
   public static void main(String[] args) {                
final String username = "s_lady@rocketmail.com";
final String password = "Password";
                //set properties
Properties props = new Properties();
props.setProperty( "mail.transport.protocol", "smtps");
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.host", "plus.smtp.mail.yahoo.com");
                props.put("mail.smtp.port", "465");
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                props.put("mail.smtp.ssl","true");
                props.put("mail.stmp.user", "username");
                props.put("mail.smtp.password", "password");
                //password authetication
Session session = Session.getInstance(props,
 new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
 });
                //send e-mail
try {

Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("s_lady@rocketmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("s_lady@rocketmail.com"));
message.setSubject("Test mail");
message.setText("Dear reciever,"
+ "\n\n No spam to my email, please!");

Transport.send(message);

System.out.println("Email Sended.");

} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}