Created
July 25, 2020 02:03
-
-
Save edylle/4d5287c5934380fbac48c62555002fd0 to your computer and use it in GitHub Desktop.
Simple Java example for sending e-mails
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
import javax.mail.Authenticator; | |
import javax.mail.Message; | |
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; | |
import java.nio.charset.StandardCharsets; | |
import java.util.List; | |
import java.util.Properties; | |
public class SendEmail { | |
private static final String NAME = "sender name"; | |
private static final String USERNAME = "sender username"; | |
private static final String PASSWORD = "sender password"; | |
private static final String HOST = "host"; | |
private static final String PORT = "port"; | |
@Override | |
public void send(List<String> emails, String subject, String text) throws Exception { | |
Properties properties = System.getProperties(); | |
properties.put("mail.smtp.auth", "true"); | |
properties.put("mail.smtp.starttls.enable", "true"); | |
properties.put("mail.smtp.host", HOST); | |
properties.put("mail.smtp.port", PORT); | |
Session session = Session.getInstance(properties, new Authenticator() { | |
protected PasswordAuthentication getPasswordAuthentication() { | |
return new PasswordAuthentication(USERNAME, PASSWORD); | |
} | |
}); | |
try { | |
MimeMessage message = new MimeMessage(session); | |
InternetAddress[] addresses = emails.stream() | |
.map(this::createInternetAddress) | |
.toArray(InternetAddress[]::new); | |
message.setFrom(new InternetAddress(USERNAME, NAME, StandardCharsets.UTF_8.name())); | |
message.addRecipients(Message.RecipientType.TO, addresses); | |
message.setSubject(subject); | |
message.setText(text); | |
Transport.send(message); | |
} catch (Exception ex) { | |
throw ex; | |
} | |
} | |
private InternetAddress createInternetAddress(String address) { | |
try { | |
return new InternetAddress(address); | |
} catch (AddressException e) { | |
throw new RuntimeException(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment