1
|
package eu.dnetlib.openaire.usermanagement.email;
|
2
|
|
3
|
import org.apache.log4j.Logger;
|
4
|
|
5
|
import javax.mail.*;
|
6
|
|
7
|
import javax.mail.internet.AddressException;
|
8
|
import javax.mail.internet.InternetAddress;
|
9
|
import javax.mail.internet.MimeMessage;
|
10
|
import java.util.Properties;
|
11
|
|
12
|
/**
|
13
|
* Created by kiatrop on 9/10/2017.
|
14
|
*/
|
15
|
public class EmailSender {
|
16
|
|
17
|
private static String username;
|
18
|
private static String password;
|
19
|
private static String host;
|
20
|
private static String port;
|
21
|
private static String from;
|
22
|
|
23
|
Logger logger = Logger.getLogger(EmailSender.class);
|
24
|
|
25
|
public void sendEmail(String recipient, String subject, String body) {
|
26
|
|
27
|
// Get system properties
|
28
|
Properties properties = System.getProperties();
|
29
|
properties.setProperty("mail.smtp.host", host);
|
30
|
properties.put("mail.smtp.port", port);
|
31
|
properties.put("mail.smtp.auth", "true"); //enable authentication
|
32
|
properties.put("mail.smtp.starttls.enable", "true");
|
33
|
|
34
|
Session session = javax.mail.Session.getInstance(properties,
|
35
|
new Authenticator() {
|
36
|
protected PasswordAuthentication getPasswordAuthentication() {
|
37
|
return new PasswordAuthentication(username, password);
|
38
|
}
|
39
|
});
|
40
|
|
41
|
try {
|
42
|
// Create a default MimeMessage object.
|
43
|
MimeMessage message = new MimeMessage(session);
|
44
|
|
45
|
// Set From: header field of the header.
|
46
|
message.setFrom(new InternetAddress(from));
|
47
|
|
48
|
// Set To: header field of the header.
|
49
|
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
|
50
|
|
51
|
// Set Subject: header field
|
52
|
message.setSubject(subject);
|
53
|
|
54
|
// For simple text setText() can be used instead of setContent()
|
55
|
|
56
|
// Send the actual HTML message, as big as you like
|
57
|
message.setContent(body, "text/html");
|
58
|
|
59
|
// Send message
|
60
|
Transport.send(message);
|
61
|
logger.debug("Sent message successfully....\n");
|
62
|
|
63
|
} catch (AddressException ae) {
|
64
|
logger.error("Email could not be send.", ae);
|
65
|
|
66
|
} catch (MessagingException me) {
|
67
|
logger.error("Email could not be send.", me);
|
68
|
}
|
69
|
}
|
70
|
}
|