use of javax.mail.Multipart in project oxCore by GluuFederation.
the class MailService method sendMail.
public boolean sendMail(SmtpConfiguration mailSmtpConfiguration, String from, String fromDisplayName, String to, String toDisplayName, String subject, String message, String htmlMessage) {
if (mailSmtpConfiguration == null) {
log.error("Failed to send message from '{}' to '{}' because the SMTP configuration isn't valid!", from, to);
return false;
}
log.debug("Host name: " + mailSmtpConfiguration.getHost() + ", port: " + mailSmtpConfiguration.getPort() + ", connection time out: " + this.connectionTimeout);
String mailFrom = from;
if (StringHelper.isEmpty(mailFrom)) {
mailFrom = mailSmtpConfiguration.getFromEmailAddress();
}
String mailFromName = fromDisplayName;
if (StringHelper.isEmpty(mailFromName)) {
mailFromName = mailSmtpConfiguration.getFromName();
}
Properties props = new Properties();
props.put("mail.smtp.host", mailSmtpConfiguration.getHost());
props.put("mail.smtp.port", mailSmtpConfiguration.getPort());
props.put("mail.from", mailFrom);
props.put("mail.smtp.connectiontimeout", this.connectionTimeout);
props.put("mail.smtp.timeout", this.connectionTimeout);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.ssl.trust", mailSmtpConfiguration.getHost());
if (mailSmtpConfiguration.isRequiresSsl()) {
props.put("mail.smtp.socketFactory.port", mailSmtpConfiguration.getPort());
props.put("mail.smtp.starttls.enable", true);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
}
Session session = null;
if (mailSmtpConfiguration.isRequiresAuthentication()) {
props.put("mail.smtp.auth", "true");
final String userName = mailSmtpConfiguration.getUserName();
final String password = mailSmtpConfiguration.getPasswordDecrypted();
session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
} else {
session = Session.getInstance(props, null);
}
MimeMessage msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(mailFrom, mailFromName));
if (StringHelper.isEmpty(toDisplayName)) {
msg.setRecipients(Message.RecipientType.TO, to);
} else {
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to, toDisplayName));
}
msg.setSubject(subject, "UTF-8");
msg.setSentDate(new Date());
if (StringHelper.isEmpty(htmlMessage)) {
msg.setText(message + "\n", "UTF-8", "plain");
} else {
// Unformatted text version
final MimeBodyPart textPart = new MimeBodyPart();
textPart.setText(message, "UTF-8", "plain");
// HTML version
final MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setText(htmlMessage, "UTF-8", "html");
// Create the Multipart. Add BodyParts to it.
final Multipart mp = new MimeMultipart("alternative");
mp.addBodyPart(textPart);
mp.addBodyPart(htmlPart);
// Set Multipart as the message's content
msg.setContent(mp);
}
Transport.send(msg);
} catch (Exception ex) {
log.error("Failed to send message", ex);
return false;
}
return true;
}
use of javax.mail.Multipart in project blogwt by billy1380.
the class EmailHelper method sendEmail.
public static boolean sendEmail(String to, String name, String subject, String body, boolean isHtml, Map<String, byte[]> attachments) {
boolean sent = false;
Property email = PropertyServiceProvider.provide().getNamedProperty(PropertyHelper.OUTGOING_EMAIL);
if (!PropertyHelper.isEmpty(email) && !PropertyHelper.NONE_VALUE.equals(email.value)) {
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
try {
Message msg = new MimeMessage(session);
InternetAddress address = new InternetAddress(email.value, PropertyServiceProvider.provide().getNamedProperty(PropertyHelper.TITLE).value);
msg.setFrom(address);
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(to, name));
msg.setSubject(subject);
if (attachments == null || attachments.size() == 0) {
if (isHtml) {
msg.setContent(body, "text/html");
} else {
msg.setText(body);
}
} else {
Multipart mp = new MimeMultipart();
MimeBodyPart content = new MimeBodyPart();
if (isHtml) {
content.setContent(body, "text/html");
} else {
content.setText(body);
}
mp.addBodyPart(content);
for (String key : attachments.keySet()) {
MimeBodyPart attachment = new MimeBodyPart();
InputStream attachmentDataStream = new ByteArrayInputStream(attachments.get(key));
attachment.setFileName(key);
attachment.setContent(attachmentDataStream, "application/pdf");
mp.addBodyPart(attachment);
}
msg.setContent(mp);
}
Transport.send(msg);
if (LOG.isLoggable(Level.INFO)) {
LOG.info("Email sent successfully.");
}
sent = true;
} catch (MessagingException | UnsupportedEncodingException e) {
LOG.log(Level.WARNING, "Error sending email [" + content(to, name, subject, body) + "]", e);
}
} else {
if (LOG.isLoggable(Level.INFO)) {
LOG.info("Property [" + PropertyHelper.OUTGOING_EMAIL + "] not configured.");
}
}
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("Email [" + content(to, name, subject, body) + "]");
}
return sent;
}
use of javax.mail.Multipart in project traccar by tananaev.
the class MailManager method sendMessage.
public void sendMessage(long userId, String subject, String body, MimeBodyPart attachment) throws MessagingException {
User user = Context.getPermissionsManager().getUser(userId);
Properties properties = null;
if (!Context.getConfig().getBoolean("mail.smtp.ignoreUserConfig")) {
properties = getProperties(new PropertiesProvider(user));
}
if (properties == null || !properties.containsKey("mail.smtp.host")) {
properties = getProperties(new PropertiesProvider(Context.getConfig()));
}
if (!properties.containsKey("mail.smtp.host")) {
LOGGER.warn("No SMTP configuration found");
return;
}
Session session = Session.getInstance(properties);
MimeMessage message = new MimeMessage(session);
String from = properties.getProperty("mail.smtp.from");
if (from != null) {
message.setFrom(new InternetAddress(from));
}
message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
message.setSubject(subject);
message.setSentDate(new Date());
if (attachment != null) {
Multipart multipart = new MimeMultipart();
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(body, "text/html; charset=utf-8");
multipart.addBodyPart(messageBodyPart);
multipart.addBodyPart(attachment);
message.setContent(multipart);
} else {
message.setContent(body, "text/html; charset=utf-8");
}
try (Transport transport = session.getTransport()) {
Main.getInjector().getInstance(StatisticsManager.class).registerMail();
transport.connect(properties.getProperty("mail.smtp.host"), properties.getProperty("mail.smtp.username"), properties.getProperty("mail.smtp.password"));
transport.sendMessage(message, message.getAllRecipients());
}
}
use of javax.mail.Multipart in project pentaho-platform by pentaho.
the class EmailComponent method executeAction.
@Override
public boolean executeAction() {
EmailAction emailAction = (EmailAction) getActionDefinition();
String messagePlain = emailAction.getMessagePlain().getStringValue();
String messageHtml = emailAction.getMessageHtml().getStringValue();
String subject = emailAction.getSubject().getStringValue();
String to = emailAction.getTo().getStringValue();
String cc = emailAction.getCc().getStringValue();
String bcc = emailAction.getBcc().getStringValue();
String from = emailAction.getFrom().getStringValue(defaultFrom);
if (from.trim().length() == 0) {
from = defaultFrom;
}
if (ComponentBase.debug) {
// $NON-NLS-1$
debug(Messages.getInstance().getString("Email.DEBUG_TO_FROM", to, from));
// $NON-NLS-1$
debug(Messages.getInstance().getString("Email.DEBUG_CC_BCC", cc, bcc));
// $NON-NLS-1$
debug(Messages.getInstance().getString("Email.DEBUG_SUBJECT", subject));
// $NON-NLS-1$
debug(Messages.getInstance().getString("Email.DEBUG_PLAIN_MESSAGE", messagePlain));
// $NON-NLS-1$
debug(Messages.getInstance().getString("Email.DEBUG_HTML_MESSAGE", messageHtml));
}
if ((to == null) || (to.trim().length() == 0)) {
// Get the output stream that the feedback is going into
OutputStream feedbackStream = getFeedbackOutputStream();
if (feedbackStream != null) {
createFeedbackParameter("to", Messages.getInstance().getString("Email.USER_ENTER_EMAIL_ADDRESS"), "", "", // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
true);
// $NON-NLS-1$
setFeedbackMimeType("text/html");
return true;
} else {
return false;
}
}
if (subject == null) {
// $NON-NLS-1$
error(Messages.getInstance().getErrorString("Email.ERROR_0005_NULL_SUBJECT", getActionName()));
return false;
}
if ((messagePlain == null) && (messageHtml == null)) {
// $NON-NLS-1$
error(Messages.getInstance().getErrorString("Email.ERROR_0006_NULL_BODY", getActionName()));
return false;
}
if (getRuntimeContext().isPromptPending()) {
return true;
}
try {
Properties props = new Properties();
final IEmailService service = PentahoSystem.get(IEmailService.class, "IEmailService", PentahoSessionHolder.getSession());
props.put("mail.smtp.host", service.getEmailConfig().getSmtpHost());
props.put("mail.smtp.port", ObjectUtils.toString(service.getEmailConfig().getSmtpPort()));
props.put("mail.transport.protocol", service.getEmailConfig().getSmtpProtocol());
props.put("mail.smtp.starttls.enable", ObjectUtils.toString(service.getEmailConfig().isUseStartTls()));
props.put("mail.smtp.auth", ObjectUtils.toString(service.getEmailConfig().isAuthenticate()));
props.put("mail.smtp.ssl", ObjectUtils.toString(service.getEmailConfig().isUseSsl()));
props.put("mail.smtp.quitwait", ObjectUtils.toString(service.getEmailConfig().isSmtpQuitWait()));
props.put("mail.from.default", service.getEmailConfig().getDefaultFrom());
String fromName = service.getEmailConfig().getFromName();
if (StringUtils.isEmpty(fromName)) {
fromName = Messages.getInstance().getString("schedulerEmailFromName");
}
props.put("mail.from.name", fromName);
props.put("mail.debug", ObjectUtils.toString(service.getEmailConfig().isDebug()));
Session session;
if (service.getEmailConfig().isAuthenticate()) {
props.put("mail.userid", service.getEmailConfig().getUserId());
props.put("mail.password", decrypt(service.getEmailConfig().getPassword()));
Authenticator authenticator = new EmailAuthenticator();
session = Session.getInstance(props, authenticator);
} else {
session = Session.getInstance(props);
}
// debugging is on if either component (xaction) or email config debug is on
if (service.getEmailConfig().isDebug() || ComponentBase.debug) {
session.setDebug(true);
}
// construct the message
MimeMessage msg = new MimeMessage(session);
if (from != null) {
msg.setFrom(new InternetAddress(from));
} else {
// There should be no way to get here
// $NON-NLS-1$
error(Messages.getInstance().getString("Email.ERROR_0012_FROM_NOT_DEFINED"));
}
if ((to != null) && (to.trim().length() > 0)) {
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
}
if ((cc != null) && (cc.trim().length() > 0)) {
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
}
if ((bcc != null) && (bcc.trim().length() > 0)) {
msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
}
if (subject != null) {
msg.setSubject(subject, LocaleHelper.getSystemEncoding());
}
EmailAttachment[] emailAttachments = emailAction.getAttachments();
if ((messagePlain != null) && (messageHtml == null) && (emailAttachments.length == 0)) {
msg.setText(messagePlain, LocaleHelper.getSystemEncoding());
} else if (emailAttachments.length == 0) {
if (messagePlain != null) {
// $NON-NLS-1$
msg.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding());
}
if (messageHtml != null) {
// $NON-NLS-1$
msg.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding());
}
} else {
// need to create a multi-part message...
// create the Multipart and add its parts to it
Multipart multipart = new MimeMultipart();
// create and fill the first message part
if (messageHtml != null) {
// create and fill the first message part
MimeBodyPart htmlBodyPart = new MimeBodyPart();
// $NON-NLS-1$
htmlBodyPart.setContent(messageHtml, "text/html; charset=" + LocaleHelper.getSystemEncoding());
multipart.addBodyPart(htmlBodyPart);
}
if (messagePlain != null) {
MimeBodyPart textBodyPart = new MimeBodyPart();
// $NON-NLS-1$
textBodyPart.setContent(messagePlain, "text/plain; charset=" + LocaleHelper.getSystemEncoding());
multipart.addBodyPart(textBodyPart);
}
for (EmailAttachment element : emailAttachments) {
IPentahoStreamSource source = element.getContent();
if (source == null) {
// $NON-NLS-1$
error(Messages.getInstance().getErrorString("Email.ERROR_0015_ATTACHMENT_FAILED"));
return false;
}
DataSource dataSource = new ActivationHelper.PentahoStreamSourceWrapper(source);
String attachmentName = element.getName();
if (ComponentBase.debug) {
// $NON-NLS-1$
debug(Messages.getInstance().getString("Email.DEBUG_ADDING_ATTACHMENT", attachmentName));
}
// create the second message part
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
// attach the file to the message
attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
attachmentBodyPart.setFileName(attachmentName);
if (ComponentBase.debug) {
// $NON-NLS-1$
debug(Messages.getInstance().getString("Email.DEBUG_ATTACHMENT_SOURCE", dataSource.getName()));
}
multipart.addBodyPart(attachmentBodyPart);
}
// add the Multipart to the message
msg.setContent(multipart);
}
// $NON-NLS-1$
msg.setHeader("X-Mailer", EmailComponent.MAILER);
msg.setSentDate(new Date());
Transport.send(msg);
if (ComponentBase.debug) {
// $NON-NLS-1$
debug(Messages.getInstance().getString("Email.DEBUG_EMAIL_SUCCESS"));
}
return true;
// TODO: persist the content set for a while...
} catch (SendFailedException e) {
// $NON-NLS-1$
error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e);
/*
* Exception ne; MessagingException sfe = e; while ((ne = sfe.getNextException()) != null && ne instanceof
* MessagingException) { sfe = (MessagingException) ne;
* error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", sfe.toString()), sfe);
* //$NON-NLS-1$ }
*/
} catch (AuthenticationFailedException e) {
// $NON-NLS-1$
error(Messages.getInstance().getString("Email.ERROR_0014_AUTHENTICATION_FAILED", to), e);
} catch (Throwable e) {
// $NON-NLS-1$
error(Messages.getInstance().getErrorString("Email.ERROR_0011_SEND_FAILED", to), e);
}
return false;
}
use of javax.mail.Multipart in project alfresco-repository by Alfresco.
the class EMLTransformer method transformLocal.
@Override
protected void transformLocal(ContentReader reader, ContentWriter writer, TransformationOptions options) throws Exception {
InputStream contentInputStream = null;
try {
contentInputStream = reader.getContentInputStream();
MimeMessage mimeMessage = new MimeMessage(Session.getDefaultInstance(new Properties()), contentInputStream);
final StringBuilder sb = new StringBuilder();
Object content = mimeMessage.getContent();
if (content instanceof Multipart) {
processMultiPart((Multipart) content, sb);
} else {
sb.append(content.toString());
}
writer.putContent(sb.toString());
} finally {
if (contentInputStream != null) {
try {
contentInputStream.close();
} catch (IOException e) {
// stop exception propagation
}
}
}
}
Aggregations