Tuesday 28 January 2014

How to send email in java - example

Leave a Comment
This is a example code to send email in java. This example will use 3rd party library JavaMail  .

The Code Example

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 zulkamal
 */
public class sendEmail {

    public static void main(String[] args) {
        final String username = "yourgmailaddress@gmail.com";
        final String password = "your password gmail";

        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("yourgmailaddress@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("recipient_email@gmail.com"));
            message.setSubject("Mail Send Using JAVA");
            message.setText("This mail is created and send through the java code,"
                    + "\n\n if you are developers, visit http://www.developersnote.com!");

            Transport.send(message);

            System.out.println("Done");

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


Example receive email


By
NOTE : – If You have Found this post Helpful, I will appreciate if you can Share it on Facebook, Twitter and Other Social Media Sites. Thanks =)

0 comments:

Post a Comment

Subscribe to our newsletter to get the latest updates to your inbox.

Your email address is safe with us!




Founder of developersnote.com, love programming and help others people. Work as Software Developer. Graduated from UiTM and continue study in Software Engineering at UTMSpace. Follow him on Twitter , or Facebook or .



Powered by Blogger.