Hackerss.com

Hackerss.com is a community of amazing hackers

Hackerss is a community for developers, data scientitst, ethical hackers, hardware enthusiasts or any person that want to learn / share their knowledge of any aspect of digital technology.

Create account Log in
hackerss
hackerss

Posted on

Send an email in Java

Send an email - Java:


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;

/**
 * This class send an email with javadoc
 * @author Juan Carlos Arcila Diaz
 * @version 1.0
 * @since 23/03/2015
 */
public class SendEmail {

    /**
     * This method send an email with javadoc
     * @param toEmail String with the email to send the message
     * @param subject String with the subject of the message
     * @param message String with the message to send
     */
    public void sendEmail(String toEmail, String subject, String message) {

        final String username = "[email protected]"; //change accordingly
        final String password = "password"; //change accordingly

        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 msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("[email protected]")); //change accordingly
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail)); //change accordingly
            msg.setSubject(subject);
            msg.setText(message);

            Transport.send(msg);

            System.out.println("Done");

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

    }

    /**
     * One Example
     */
    public static void main(String[] args) {

        SendEmail sendEmail = new SendEmail();

        //Example 
        sendEmail.sendEmail("[email protected]", "Test", "Test Message");

    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)