Wednesday, June 19, 2013

Java - Mail

How to send mail from Java sourcecode?
First you need to download the library mail.jar from oracle and add it to your Java project.
You can get it on the link below:
http://www.oracle.com/technetwork/java/index-138643.html

Than try out this code:
final String username = "username@gmail.com";
final String password = "password";

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");

Session session = Session.getInstance(props,
  new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(username, password);
    }
  });

try {

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("from-email@gmail.com"));
    message.setRecipients(Message.RecipientType.TO,
        InternetAddress.parse("to-email@gmail.com"));
    message.setSubject("Testing Subject");
    message.setText("Dear Mail Crawler,"
        + "\n\n No spam to my email, please!");

    Transport.send(message);

    System.out.println("Done");

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


It's quite easy and it should work, unless your firewall blocks it, in that case open the port 587.
This is working for GMail accounts, but it should work with other accounts too, with just a little modification in the code.
This example code is copied from mkyong's website:
http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/comment-page-4/#comment-135038

No comments:

Post a Comment

NSNotification example