Wednesday, June 17, 2009

Simple Java Mail SMTP Client

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

class SimpleMail {
static Message emailMessage;

public static void main(String[] args) {

try {

emailMessage = new MimeMessage(createSession());
// replace this with the TO mail address
InternetAddress add = new InternetAddress("receipeicnt@abc.com");
InternetAddress[] addresses = new InternetAddress[1];
addresses[0] = new InternetAddress("d");
emailMessage.setFrom(add);
emailMessage.setRecipients(javax.mail.Message.RecipientType.TO,
addresses);
emailMessage.setSubject("My Subject ");
emailMessage.setContent("My First Mail", "text/plain");
emailMessage.saveChanges();

Transport.send(emailMessage);

} catch (AddressException e) {

e.printStackTrace();
} catch (MessagingException e) {

e.printStackTrace();
}

}

private static Session createSession() {

Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "your_mail_server_IP");

// If your sending multiple mails and even if one mail fails this by
// setting
// this property all the other mails except that mail will still be
// delievered
props.put("mail.smtp.sendpartial", "true");

Authenticator authenticator = null;

props.put("mail.smtp.auth", "true");
// enter your mail address and password here
authenticator = new MessagingAuthenticator("xxx@abc.com", "password");

return Session.getDefaultInstance(props, authenticator);
}
}

class MessagingAuthenticator extends Authenticator {
private String userName;
private String password;

public MessagingAuthenticator(String userName, String password) {
this.userName = userName;
this.password = password;
}

public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
}

1 comment: