Tags in my blog

16 April 2009

Send email with JavaMail

Require to download mail.jar and activation.jar from JavaMail library.

Example:

Main.java

package sendmail;

import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
*
* @author Stefan
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
String host = "mail.hostname.com";
String from = "user1@hostname.com";
String to = "user2@hostname.com";
Properties props = new Properties();
props.put("mail.smtp.host", host);
Authenticator auth = new MyAuth();
Session session = Session.getDefaultInstance(props, auth);
MimeMessage message = new MimeMessage(session);
try {
Address addressFrom = new InternetAddress(from);
Address addressTo = new InternetAddress(to);
message.setText("Hello");
message.setSubject("First");
message.setFrom(addressFrom);
message.addRecipient(RecipientType.TO, addressTo);
Transport.send(message);
} catch (MessagingException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
}
}


MyAuth.java

package sendmail;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

/**
*
* @author Stefan
*/
public class MyAuth extends Authenticator {

@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("user1@hostname.com", "password");
}
}

No comments: