-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathEmailUtility.java
More file actions
59 lines (49 loc) · 1.89 KB
/
EmailUtility.java
File metadata and controls
59 lines (49 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.occamlab.te.web;
import java.util.Date;
import java.util.Properties;
import java.util.Random;
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;
public class EmailUtility {
public static void sendEmail(String host, String portNo, final String userName, final String pwd, String toAddress,
String subject, String message) throws AddressException, MessagingException {
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", portNo);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// see https://bugs.openjdk.org/browse/JDK-8202343
properties.put("mail.smtp.ssl.protocols", "TLSv1.2");
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, pwd);
}
};
Session session = Session.getInstance(properties, auth);
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setContent(message, "text/html; charset=utf-8");
Transport.send(msg);
}
catch (Exception e) {
throw new RuntimeException("Failed send mail : " + e.getMessage());
}
}
public static String getRandomNumberString() {
Random randomNo = new Random();
int number = randomNo.nextInt(999999);
return String.format("%06d", number);
}
}