Gradle dependency
compile group: 'com.sun.mail', name: 'javax.mail', version: '1.6.2'
Import to the Class File
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
The Template
// Recipient's email ID needs to be mentioned.
String to = <RECIPIENTS_EMAIL>;
//Sender's email ID needs to be mentioned
String from = <SENDERS_EMAIL>;
//The subject of the email.
String subject = <EMAIL_SUBJECT>;
//The body of the email.
String body = <EMAIL_BODY>;
//SMTP Server
final String host = <SMTP_SERVER>;
//SMTP Port
final String port = <SMTP_PORT>;
//SMTP Username
final String username = <USERNAME>;
//SMTP Password
final String password = <PASSWORD>;
try {
//SMTP Configuration
Properties props = new Properties();
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
// Create a session object.
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
}
);
// Create a message object.
Message message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
// Set Subject: header field
message.setSubject(subject);
// Now set the actual message
message.setText(body);
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
Recent Comments