下面列出了怎么用javax.mail.Authenticator的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* connects securely to the SMTP server (with authentication)
*
* @return the SMTP session
*/
private Session connectAuthenticatedToServer() {
Properties props = new Properties();
props.put("mail.smtp.host", smtpserver); // SMTP Host
props.put("mail.smtp.socketFactory.port", port); // SSL Port
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // SSL Factory Class
props.put("mail.smtp.auth", "true"); // Enabling SMTP Authentication
props.put("mail.smtp.port", port); // SMTP Port
Authenticator auth = new Authenticator() {
// override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
};
Session session = Session.getDefaultInstance(props, auth);
return session;
}
/**
* 创建session
*
* @author lidoudou
* @date 2019/2/16 14:59
*/
private static Session createSSLSession(String sendSMTPHost, String port, String userName, String pwd) {
// 1. 创建参数配置, 用于连接邮件服务器的参数配置
Properties props = new Properties(); // 参数配置
props.setProperty("mail.smtp.user", userName);
props.setProperty("mail.smtp.password", pwd);
props.setProperty("mail.smtp.host", sendSMTPHost);
props.setProperty("mail.smtp.port", port);
props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.socketFactory.port", port);
props.put("mail.smtp.auth", "true");
// 2. 根据配置创建会话对象, 用于和邮件服务器交互
Session session = Session.getDefaultInstance(props, new Authenticator() {
//身份认证
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, pwd);
}
});
session.setDebug(true); // 设置为debug模式, 可以查看详细的发送 log
return session;
}
public void sendErrorEmail(String emailTo, String emailFrom, String smtpServer, String subject,
String msg, String password, Integer port) throws IOException {
Properties props = new Properties();
props.put("mail.smtp.host", smtpServer); // SMTP Host
props.put("mail.smtp.socketFactory.port", port); // SSL Port
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // SSL Factory
// Class
props.put("mail.smtp.auth", "true"); // Enabling SMTP Authentication
props.put("mail.smtp.port", port); // SMTP Port, gmail 465
Authenticator auth = new Authenticator() {
// override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailFrom, password);
}
};
Session session = Session.getDefaultInstance(props, auth);
Thread eMailThread = new Thread(new EMailUtil(session, emailTo, subject, msg));
eMailThread.start();
}
private Session getSession() {
if(session == null) {
final String fromEmail = environment.getProperty("from.email");
final String password = environment.getProperty("email.password");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Authenticator auth = new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
this.session = Session.getInstance(props, auth);
}
return session;
}
/**
* Based on the input properties, determine whether an authenticate or unauthenticated session should be used. If authenticated, creates a Password Authenticator for use in sending the email.
*
* @param properties mail properties
* @return session
*/
private Session createMailSession(final Properties properties) {
String authValue = properties.getProperty("mail.smtp.auth");
Boolean auth = Boolean.valueOf(authValue);
/*
* Conditionally create a password authenticator if the 'auth' parameter is set.
*/
final Session mailSession = auth ? Session.getInstance(properties, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
String username = properties.getProperty("mail.smtp.user"), password = properties.getProperty("mail.smtp.password");
return new PasswordAuthentication(username, password);
}
}) : Session.getInstance(properties); // without auth
return mailSession;
}
/**
* Based on the input properties, determine whether an authenticate or unauthenticated session should be used. If authenticated, creates a Password Authenticator for use in sending the email.
*
* @param properties mail properties
* @return session
*/
private Session createMailSession(final Properties properties) {
String authValue = properties.getProperty("mail.smtp.auth");
Boolean auth = Boolean.valueOf(authValue);
/*
* Conditionally create a password authenticator if the 'auth' parameter is set.
*/
final Session mailSession = auth ? Session.getInstance(properties, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
String username = properties.getProperty("mail.smtp.user"), password = properties.getProperty("mail.smtp.password");
return new PasswordAuthentication(username, password);
}
}) : Session.getInstance(properties); // without auth
return mailSession;
}
/**
* Reads mail properties creates a JavaMail session that will be used to
* send all mail.
*/
public EmailTask(String host, String port, String debug, String user, String password, String from) {
this();
Properties mailProps = new Properties();
if (host != null) {
mailProps.setProperty("mail.smtp.host", host);
}
// check the port for errors (if specified)
if (port != null && !port.equals("")) {
try {
// no errors at this point, so add the port as a property
mailProps.setProperty("mail.smtp.port", port);
} catch (Exception e) {
}
}
// optional mail debug (output is written to standard out)
if ("true".equals(debug)) {
mailProps.setProperty("mail.debug", "true");
}
mailProps.put("mail.smtp.auth", "true");
mailProps.put("mail.smtp.from", from);
// Create the mail session
Authenticator auth = new SMTPAuthenticator(user, password);
session = Session.getDefaultInstance(mailProps, auth);
}
/**
* Create the {@link Session} at startup
*/
@Override
public void start()
{
final Properties props = new Properties();
props.put("mail.smtp.host", EmailPreferences.mailhost);
props.put("mail.smtp.port", EmailPreferences.mailport);
final String username = EmailPreferences.username;
final String password = EmailPreferences.password;
if (!username.isEmpty() && !password.isEmpty()) {
PasswordAuthentication auth = new PasswordAuthentication(username, password);
session = Session.getDefaultInstance(props, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return auth;
}
});
} else {
session = Session.getDefaultInstance(props);
}
}
public boolean sendMsg(String recipient, String subject, String content)
throws MessagingException {
// Create a mail object
Session session = Session.getInstance(props, new Authenticator() {
// Set the account information session,transport will send mail
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(Constants.MAIL_USERNAME, Constants.MAIL_PASSWORD);
}
});
session.setDebug(true);
Message msg = new MimeMessage(session);
try {
msg.setSubject(subject); //Set the mail subject
msg.setContent(content,"text/html;charset=utf-8");
msg.setFrom(new InternetAddress(Constants.MAIL_USERNAME)); //Set the sender
msg.setRecipient(RecipientType.TO, new InternetAddress(recipient)); //Set the recipient
Transport.send(msg);
return true;
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
return false;
}
}
/**
Outgoing Mail (SMTP) Server
requires TLS or SSL: smtp.gmail.com (use authentication)
Use Authentication: Yes
Port for TLS/STARTTLS: 587
*/
public static void main(String[] args) {
final String fromEmail = "[email protected]";
final String password = "Tata!!11";
final String toEmail = "[email protected]";
System.out.println("TLSEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
props.put("mail.smtp.port", "587"); //TLS Port
props.put("mail.smtp.auth", "true"); //enable authentication
props.put("mail.smtp.starttls.enable", "true"); //enable STARTTLS
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getInstance(props, auth);
EmailUtil.sendEmail(session, toEmail,"TLSEmail Testing Subject", "TLSEmail Testing Body");
}
/**
* initialize java mail session
*/
private void initMailSession() {
address = prop.getProperty(EMAIL_ADDRESS);
String host = prop.getProperty(EMAIL_HOST);
final String user = prop.getProperty(EMAIL_USER);
final String password = prop.getProperty(EMAIL_PASSWORD);
String protocol = prop.getProperty(EMAIL_PROTOCOL);
emailProp = new Properties();
emailProp.setProperty("mail.store.protocol", protocol);
emailProp.setProperty("mail.host", host);
emailProp.setProperty("mail.user", user);
emailProp.setProperty("mail.from", address);
emailProp.setProperty("mail.debug", "true");
mailSession = Session.getInstance(emailProp, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
});
}
public void sendErrorEmail(String emailTo, String emailFrom, String smtpServer, String subject,
String msg, String password, Integer port) throws IOException {
Properties props = new Properties();
props.put("mail.smtp.host", smtpServer); // SMTP Host
props.put("mail.smtp.socketFactory.port", port); // SSL Port
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // SSL Factory
// Class
props.put("mail.smtp.auth", "true"); // Enabling SMTP Authentication
props.put("mail.smtp.port", port); // SMTP Port, gmail 465
Authenticator auth = new Authenticator() {
// override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(emailFrom, password);
}
};
Session session = Session.getDefaultInstance(props, auth);
Thread eMailThread = new Thread(new EMailUtil(session, emailTo, subject, msg));
eMailThread.start();
}
public EagleMailClient(AbstractConfiguration configuration) {
try {
ConcurrentMapConfiguration con = (ConcurrentMapConfiguration)configuration;
velocityEngine = new VelocityEngine();
velocityEngine.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
velocityEngine.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
velocityEngine.init();
con.setProperty("mail.transport.protocol", "smtp");
final Properties config = con.getProperties();
if(Boolean.parseBoolean(config.getProperty(AUTH_CONFIG))){
session = Session.getDefaultInstance(config, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(config.getProperty(USER_CONFIG), config.getProperty(PWD_CONFIG));
}
});
}
else session = Session.getDefaultInstance(config, new Authenticator() {});
final String debugMode = config.getProperty(DEBUG_CONFIG, "false");
final boolean debug = Boolean.parseBoolean(debugMode);
session.setDebug(debug);
} catch (Exception e) {
LOG.error("Failed connect to smtp server",e);
}
}
@Override
public Authenticator build() {
boolean isUpdatable = updatableValueBuilder.getValue(false);
if (isUpdatable) {
if (usernameValueBuilder.hasValueOrProperties() && passwordValueBuilder.hasValueOrProperties()) {
return buildContext.register(new UpdatableUsernamePasswordAuthenticator(usernameValueBuilder, passwordValueBuilder));
}
return null;
}
String u = usernameValueBuilder.getValue();
String p = passwordValueBuilder.getValue();
if (u != null && p != null) {
return buildContext.register(new UsernamePasswordAuthenticator(u, p));
}
return null;
}
/**
* Based on the input properties, determine whether an authenticate or unauthenticated session should be used. If authenticated, creates a Password Authenticator for use in sending the email.
*
* @param properties mail properties
* @return session
*/
private Session createMailSession(final Properties properties) {
String authValue = properties.getProperty("mail.smtp.auth");
Boolean auth = Boolean.valueOf(authValue);
/*
* Conditionally create a password authenticator if the 'auth' parameter is set.
*/
final Session mailSession = auth ? Session.getInstance(properties, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
String username = properties.getProperty("mail.smtp.user"), password = properties.getProperty("mail.smtp.password");
return new PasswordAuthentication(username, password);
}
}) : Session.getInstance(properties); // without auth
return mailSession;
}
/**
* Based on the input properties, determine whether an authenticate or unauthenticated session should be used. If authenticated, creates a Password Authenticator for use in sending the email.
*
* @param properties mail properties
* @return session
*/
private Session createMailSession(final Properties properties) {
String authValue = properties.getProperty("mail.smtp.auth");
Boolean auth = Boolean.valueOf(authValue);
/*
* Conditionally create a password authenticator if the 'auth' parameter is set.
*/
final Session mailSession = auth ? Session.getInstance(properties, new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
String username = properties.getProperty("mail.smtp.user"), password = properties.getProperty("mail.smtp.password");
return new PasswordAuthentication(username, password);
}
}) : Session.getInstance(properties); // without auth
return mailSession;
}
/**
* 此段代码用来发送普通电子邮件
*
* @throws MessagingException
* @throws UnsupportedEncodingException
* @throws UnsupportedEncodingException
*/
public void send() throws MessagingException, UnsupportedEncodingException {
Properties props = new Properties();
Authenticator auth = new Email_Autherticator(); // 进行邮件服务器用户认证
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, auth);
// 设置session,和邮件服务器进行通讯。
MimeMessage message = new MimeMessage(session);
// message.setContent("foobar, "application/x-foobar"); // 设置邮件格式
message.setSubject(mail_subject); // 设置邮件主题
message.setText(mail_body); // 设置邮件正文
message.setHeader(mail_head_name, mail_head_value); // 设置邮件标题
message.setSentDate(new Date()); // 设置邮件发送日期
Address address = new InternetAddress(mail_from, personalName);
message.setFrom(address); // 设置邮件发送者的地址
Address toAddress = new InternetAddress(mail_to); // 设置邮件接收方的地址
message.addRecipient(Message.RecipientType.TO, toAddress);
Transport.send(message); // 发送邮件
}
@BeforeEach
@SuppressWarnings("unused")
void setUp() {
session = mock(Session.class);
new MockUp<Session>() {
@Mock
Session getInstance(Properties props, Authenticator authenticator) {
return session;
}
};
sourceIndex = mock(Index.class);
doReturn(".").when(sourceIndex).getFolderSeparator();
doReturn("InBox").when(sourceIndex).getInbox();
targetIndex = mock(Index.class);
doReturn("|").when(targetIndex).getFolderSeparator();
doReturn("inbox").when(targetIndex).getInbox();
}
@PostConstruct
private void init(){
String mailhostType = Configurations.getConfigurationProperty("poc.cfg.property.mailhost.type");
//Set mail configurations
Properties properties = System.getProperties();
properties.setProperty("mail.transport.protocol", "smtp");
properties.setProperty("mail.smtp.host",
Configurations.getConfigurationProperty("poc.cfg.property.mailhost"));
properties.setProperty("mail.smtp.port",
Configurations.getConfigurationProperty("poc.cfg.property.mail.smtp.port"));
properties.setProperty("mail.smtp.from",
Configurations.getConfigurationProperty("poc.cfg.property.smtp.from"));
properties.setProperty("mail.smtp.auth", String.valueOf(!mailhostType.equalsIgnoreCase("SendMail")));
Authenticator auth = new PasswordAuthenticator(
Configurations.getConfigurationProperty("poc.cfg.property.smtp.auth.user"),
Configurations.getConfigurationProperty("poc.cfg.property.smtp.auth.password"));
//TLS
if(mailhostType.equalsIgnoreCase("StartTLS")){
properties.setProperty("mail.smtp.starttls.enable", "true");
session = Session.getInstance(properties, auth);
}
//SSL
else if(mailhostType.equalsIgnoreCase("SSL")){
properties.setProperty("mail.smtp.ssl.enable", "true");
session = Session.getInstance(properties, auth);
}
else{
session = Session.getInstance(properties);
}
}
public static void putBoth(String key, Properties properties){
putProperties(key, properties);
// 此处要用 Session#getInstance,Session#getDefaultInstance 为单例
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(properties.getProperty("mail.username"),
properties.getProperty("mail.password"));
}
});
if(null != properties.getProperty("mail.debug")){
session.setDebug(Boolean.valueOf(properties.getProperty("mail.debug")));
}
putSession(key, session);
}
/**
* Send Mail Alert.
*
* @param Message
*/
public static void sendMail(String messageText, String toMail, String subject){
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", propertyUtil.getValue(SurveillerConstants.MAIL_SERVER_IP));
props.put("mail.smtp.port", propertyUtil.getValue(SurveillerConstants.MAIL_SERVER_PORT));
Session session = null;
String mailAuthUserName = propertyUtil.getValue(SurveillerConstants.MAIL_SERVER_USERNAME);
String mailAuthPassword = propertyUtil.getValue(SurveillerConstants.MAIL_SERVER_PASSWORD);
if (mailAuthUserName != null && mailAuthUserName.length() > 0 && mailAuthPassword != null
&& mailAuthPassword.length() > 0) {
props.put("mail.smtp.auth", "true");
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(mailAuthUserName, mailAuthPassword);
}
};
session = Session.getDefaultInstance(props, auth);
} else {
props.put("mail.smtp.auth", "false");
session = Session.getInstance(props);
}
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(propertyUtil.getValue(SurveillerConstants.MAIL_FROM_ADDRESS) ));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toMail));
message.setSubject(subject);
message.setText(messageText);
Transport.send(message);
} catch (MessagingException me) {
logger.error("Error in Mail Sending: " + me);
throw new RuntimeException(me.getMessage());
}
logger.debug("Mail Sent to: " + toMail);
}
/**
* 发送文本邮件
*/
public static void sendTextEmail(Authenticator authenticator, String hostName, Tuple2<String, String> fromInfo, List<Tuple2<String, String>> toList, List<Tuple2<String, String>> ccList, String subject, String textContent) throws EmailException {
SimpleEmail simpleEmail = buildSimpleEmail(authenticator, hostName, fromInfo, toList, ccList, subject);
simpleEmail.setMsg(textContent);
simpleEmail.send();
}
/**
* 发送HTML格式邮件
*/
public static void sendHtmlEmail(Authenticator authenticator, String hostName, Tuple2<String, String> fromInfo, List<Tuple2<String, String>> toList, List<Tuple2<String, String>> ccList, String subject, String htmlContent) throws EmailException {
HtmlEmail htmlEmail = buildHtmlEmail(authenticator, hostName, fromInfo, toList, ccList, subject);
htmlEmail.setHtmlMsg(htmlContent);
htmlEmail.send();
}
public static void putBoth(String key, Properties properties){
putProperties(key, properties);
// 此处要用 Session#getInstance,Session#getDefaultInstance 为单例
Session session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(properties.getProperty("mail.username"),
properties.getProperty("mail.password"));
}
});
if(null != properties.getProperty("mail.debug")){
session.setDebug(Boolean.valueOf(properties.getProperty("mail.debug")));
}
putSession(key, session);
}
public EmailSender(PinCodeOptions.SMTPOptions smtpOptions) {
if (smtpOptions != null) {
Properties properties = new Properties();
properties.setProperty("mail.user", smtpOptions.username);
properties.setProperty("mail.password", smtpOptions.password);
properties.setProperty("mail.debug", "true");
properties.setProperty("mail.smtp.auth", "true");
properties.setProperty("mail.smtp.host", smtpOptions.host);
properties.setProperty("mail.smtp.port", String.valueOf(smtpOptions.port));
properties.setProperty("mail.transport.protocol", "smtp");
properties.setProperty("mail.mime.charset", "UTF-8");
properties.setProperty("mail.replyTo", smtpOptions.replyTo);
if (smtpOptions.starttlsEnabled != null) {
properties.put("mail.smtp.starttls.enable", smtpOptions.starttlsEnabled);
}
if (smtpOptions.sslEnabled != null) {
properties.put("mail.smtp.ssl.enable", smtpOptions.sslEnabled);
}
properties.put("mail.smtp.socketFactory.port", smtpOptions.port);
properties.put("mail.smtp.ssl.socketFactory", "javax.net.ssl.SSLSocketFactory");
this.session = Session.getInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(properties.getProperty("mail.user"), properties.getProperty("mail.password"));
}
});
} else {
this.session = null;
}
}
public EmailInvite(final String smtpHost, final int smtpPort, final boolean smtpUseAuth, final String smtpUsername, final String smtpPassword, final String emailSender,
final boolean smtpDebug) {
_smtpHost = smtpHost;
_smtpPort = smtpPort;
_smtpUseAuth = smtpUseAuth;
_smtpUsername = smtpUsername;
_smtpPassword = smtpPassword;
_emailSender = emailSender;
if (_smtpHost != null) {
final Properties smtpProps = new Properties();
smtpProps.put("mail.smtp.host", smtpHost);
smtpProps.put("mail.smtp.port", smtpPort);
smtpProps.put("mail.smtp.auth", "" + smtpUseAuth);
if (smtpUsername != null) {
smtpProps.put("mail.smtp.user", smtpUsername);
}
smtpProps.put("mail.smtps.host", smtpHost);
smtpProps.put("mail.smtps.port", smtpPort);
smtpProps.put("mail.smtps.auth", "" + smtpUseAuth);
if (smtpUsername != null) {
smtpProps.put("mail.smtps.user", smtpUsername);
}
if ((smtpUsername != null) && (smtpPassword != null)) {
_smtpSession = Session.getInstance(smtpProps, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(smtpUsername, smtpPassword);
}
});
} else {
_smtpSession = Session.getInstance(smtpProps);
}
_smtpSession.setDebug(smtpDebug);
} else {
_smtpSession = null;
}
}
/**
Outgoing Mail (SMTP) Server
requires TLS or SSL: smtp.gmail.com (use authentication)
Use Authentication: Yes
Port for SSL: 465
*/
public static void main(String[] args) {
final String fromEmail = "[email protected]";
final String password = "my_pwd";
final String toEmail = "[email protected]";
System.out.println("SSLEmail Start");
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
props.put("mail.smtp.socketFactory.port", "465"); //SSL Port
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory"); //SSL Factory Class
props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
props.put("mail.smtp.port", "465"); //SMTP Port
Authenticator auth = new Authenticator() {
//override the getPasswordAuthentication method
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(fromEmail, password);
}
};
Session session = Session.getDefaultInstance(props, auth);
System.out.println("Session created");
EmailUtil.sendEmail(session, toEmail,"SSLEmail Testing Subject", "SSLEmail Testing Body");
EmailUtil.sendAttachmentEmail(session, toEmail,"SSLEmail Testing Subject with Attachment", "SSLEmail Testing Body with Attachment");
EmailUtil.sendImageEmail(session, toEmail,"SSLEmail Testing Subject with Image", "SSLEmail Testing Body with Image");
}
private Session createSession() {
Properties props = new Properties();
if (IBMonitorSvc.emailUser.isEmpty() || IBMonitorSvc.emailUser.equals("")) {
props.setProperty("mail.smtp.host", IBMonitorSvc.emailHost);
props.setProperty("mail.smtp.port", String.valueOf(IBMonitorSvc.emailPort));
props.setProperty("mail.smtp.auth", "false");
props.setProperty("mail.transport.protocol", "smtp");
if (IBMonitorSvc.emailPort == 25) {
props.setProperty("mail.smtp.starttls.enable","false"); //Important: must start TLS
} else {
props.setProperty("mail.smtp.starttls.enable","true"); //Important: must start TLS
}
} else {
props.setProperty("mail.smtp.host", IBMonitorSvc.emailHost);
props.setProperty("mail.smtp.port", String.valueOf(IBMonitorSvc.emailPort));
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.starttls.enable","true"); //Important: must start TLS
}
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
session.setDebug(false);
return session;
}
@Override
protected void doInitialize(UimaContext context) throws ResourceInitializationException {
validateParams();
Authenticator authenticator =
new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pass);
}
};
Properties prop = new Properties();
prop.put("mail.store.protocol", protocol);
prop.put("mail.host", server);
prop.put("mail." + protocol + ".port", port);
prop.put("mail.user", user);
Session session = Session.getInstance(prop, authenticator);
try {
store = session.getStore();
} catch (NoSuchProviderException e) {
throw new ResourceInitializationException(e);
}
try {
store.connect();
inboxFolder = store.getFolder(inbox);
reopenConnection();
} catch (MessagingException me) {
throw new ResourceInitializationException(me);
}
}
@VisibleForTesting
MailSessionProvider(Map<String, String> mailConfiguration) {
if (mailConfiguration != null && !mailConfiguration.isEmpty()) {
Properties props = new Properties();
mailConfiguration.forEach(props::setProperty);
if (Boolean.parseBoolean(props.getProperty("mail.smtp.auth"))) {
final String username = props.getProperty("mail.smtp.auth.username");
final String password = props.getProperty("mail.smtp.auth.password");
// remove useless properties
props.remove("mail.smtp.auth.username");
props.remove("mail.smtp.auth.password");
this.session =
Session.getInstance(
props,
new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
} else {
this.session = Session.getInstance(props);
}
} else {
LOG.warn("Mail server is not configured. Cannot send emails.");
this.session = null;
}
}