Created
February 1, 2020 07:34
-
-
Save teguhteja/07f8dcd9098ea5f591d0ccbbc8adb275 to your computer and use it in GitHub Desktop.
Servlet for sending enail
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* To change this license header, choose License Headers in Project Properties. | |
* To change this template file, choose Tools | Templates | |
* and open the template in the editor. | |
*/ | |
package email; | |
/** | |
* | |
* @author teguhteja | |
*/ | |
import java.util.Date; | |
import java.util.Properties; | |
import javax.mail.Authenticator; | |
import javax.mail.Message; | |
import javax.mail.MessagingException; | |
import javax.mail.PasswordAuthentication; | |
import javax.mail.Session; | |
import javax.mail.Transport; | |
import javax.mail.internet.AddressException; | |
import javax.mail.internet.InternetAddress; | |
import javax.mail.internet.MimeMessage; | |
/** | |
* A utility class for sending e-mail messages | |
* @author www.codejava.net | |
* | |
*/ | |
public class EmailUtility { | |
public static void sendEmail(String host, String port, | |
final String userName, final String password, String toAddress, | |
String subject, String message) throws AddressException, | |
MessagingException { | |
// sets SMTP server properties | |
Properties properties = new Properties(); | |
properties.put("mail.smtp.host", host); | |
properties.put("mail.smtp.port", port); | |
properties.put("mail.smtp.auth", "true"); | |
properties.put("mail.smtp.starttls.enable", "true"); | |
// creates a new session with an authenticator | |
Authenticator auth = new Authenticator() { | |
public PasswordAuthentication getPasswordAuthentication() { | |
return new PasswordAuthentication(userName, password); | |
} | |
}; | |
Session session = Session.getInstance(properties, auth); | |
// creates a new e-mail message | |
Message msg = new MimeMessage(session); | |
msg.setFrom(new InternetAddress(userName)); | |
InternetAddress[] toAddresses = { new InternetAddress(toAddress) }; | |
msg.setRecipients(Message.RecipientType.TO, toAddresses); | |
msg.setSubject(subject); | |
msg.setSentDate(new Date()); | |
msg.setText(message); | |
// sends the e-mail | |
Transport.send(msg); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment