String mailHost = servletConfig.getServletContext().getInitParameter(
"mailHost"
);
String mailTo = servletConfig.getServletContext().getInitParameter(
"mailTo"
);
String mailFrom = servletConfig.getServletContext().getInitParameter(
"mailFrom"
);
String mailUser = servletConfig.getServletContext().getInitParameter(
"mailUser"
);
String mailPassword = servletConfig.getServletContext().getInitParameter(
"mailPassword"
);
String mailTls = servletConfig.getServletContext().getInitParameter(
"mailTls"
);
String mailSsl = servletConfig.getServletContext().getInitParameter(
"mailSsl"
);
String mailPort = servletConfig.getServletContext().getInitParameter(
"mailPort"
);
String mailDebug = servletConfig.getServletContext().getInitParameter(
"mailDebug"
);
if
(mailHost ==
null
|| mailTo ==
null
|| mailFrom ==
null
) {
throw
new
ServletException(
"Unable to get mail init parameters"
);
}
StringBuilder message =
new
StringBuilder(
"Start messagen"
);
message.apppend(
"line by line construct the message"
);
Properties mailProperties = System.getProperties();
mailProperties.put(
"mail.transport.protocol"
,
"smtp"
);
mailProperties.put(
"mail.smtp.host"
, mailHost);
if
(mailPort !=
null
) {
mailProperties.put(
"mail.smtp.port"
, mailPort);
}
if
(mailSsl !=
null
) {
mailProperties.put(
"mail.smtp.ssl.enable"
,
"true"
);
mailProperties.put(
"mail.smtp.ssl.trust"
,
"*"
);
if
(mailPort !=
null
) {
mailProperties.put(
"mail.smtp.socketFactory.port"
, mailPort);
}
else
{
mailProperties.put(
"mail.smtp.socketFactory.port"
,
"465"
);
}
mailProperties.put(
"mail.smtp.socketFactory.class"
,
"javax.net.ssl.SSLSocketFactory"
);
mailProperties.put(
"mail.smtp.socketFactory.fallback"
,
"false"
);
}
if
(mailDebug !=
null
&& mailDebug.equals(
"yes"
)) {
mailProperties.put(
"mail.debug"
,
"true"
);
}
if
(mailTls !=
null
&& mailTls.equals(
"yes"
)) {
mailProperties.put(
"mail.smtp.starttls.enable"
,
"true"
);
}
Session mailSession;
if
(mailUser !=
null
) {
mailProperties.put(
"mail.smtp.auth"
,
true
);
mailSession = Session.getInstance(mailProperties,
new
SMTPAuthenticator(mailUser, mailPassword));
}
else
{
mailSession = Session.getInstance(mailProperties,
null
);
}
try
{
Message mailMessage =
new
MimeMessage(mailSession);
mailMessage.setFrom(
new
InternetAddress(mailFrom));
mailMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailTo,
false
));
mailMessage.setSubject(
"Email subject"
);
mailMessage.setText(message.toString());
mailMessage.setHeader(
"X-Mailer"
,
"JavaMail"
);
mailMessage.setSentDate(
new
Date());
Transport.send(mailMessage);
}
catch
(javax.mail.internet.AddressException ex) {
throw
new
ServletException(
"Unable to prepare mail message"
, ex);
}
catch
(javax.mail.MessagingException ex) {
throw
new
ServletException(
"Unable to send mail message"
, ex);
}