use of javax.mail.Multipart in project opennms by OpenNMS.
the class JavaMailAckReaderIT method workingWithMultiPartMessages.
/**
* tests the ability to create acknowledgments from an email for a multi-part text. This test
* creates a message from scratch rather than reading from an inbox. This message creation
* may not actually represent what comes from a mail server.
*/
@Test
public void workingWithMultiPartMessages() throws JavaMailerException, MessagingException {
List<Message> msgs = new ArrayList<>();
Properties props = new Properties();
Message msg = new MimeMessage(Session.getDefaultInstance(props));
Address[] addrs = new Address[1];
addrs[0] = new InternetAddress("david@opennms.org");
msg.addFrom(addrs);
msg.addRecipient(RecipientType.TO, new InternetAddress("david@opennms.org"));
msg.setSubject("Re: Notice #1234 JavaMailReaderImplTest Test Message");
Multipart mpContent = new MimeMultipart();
BodyPart textBp = new MimeBodyPart();
BodyPart htmlBp = new MimeBodyPart();
textBp.setText("ack");
htmlBp.setContent("<html>\n" + " <head>\n" + " <title>\n" + " Acknowledge\n" + " </title>\n" + " </head>\n" + " <body>\n" + " <h1>\n" + " ack\n" + " </h1>\n" + " </body>\n" + "</html>", "text/html");
mpContent.addBodyPart(textBp);
mpContent.addBodyPart(htmlBp);
msg.setContent(mpContent);
msgs.add(msg);
List<OnmsAcknowledgment> acks = m_processor.createAcks(msgs);
Assert.assertEquals(1, acks.size());
Assert.assertEquals(AckType.NOTIFICATION, acks.get(0).getAckType());
Assert.assertEquals("david@opennms.org", acks.get(0).getAckUser());
Assert.assertEquals(AckAction.ACKNOWLEDGE, acks.get(0).getAckAction());
Assert.assertEquals(new Integer(1234), acks.get(0).getRefId());
}
use of javax.mail.Multipart in project Lucee by lucee.
the class SMTPClient method createMimeMessage.
private MimeMessageAndSession createMimeMessage(lucee.runtime.config.Config config, String hostName, int port, String username, String password, long lifeTimesan, long idleTimespan, boolean tls, boolean ssl, boolean sendPartial, boolean newConnection, boolean userset) throws MessagingException {
Properties props = (Properties) System.getProperties().clone();
String strTimeout = Caster.toString(getTimeout(config));
props.put("mail.smtp.host", hostName);
props.put("mail.smtp.timeout", strTimeout);
props.put("mail.smtp.connectiontimeout", strTimeout);
props.put("mail.smtp.sendpartial", Caster.toString(sendPartial));
props.put("mail.smtp.userset", userset);
if (port > 0) {
props.put("mail.smtp.port", Caster.toString(port));
}
if (ssl) {
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.port", Caster.toString(port));
props.put("mail.smtp.socketFactory.fallback", "false");
} else {
props.put("mail.smtp.socketFactory.class", "javax.net.SocketFactory");
props.remove("mail.smtp.socketFactory.port");
props.remove("mail.smtp.socketFactory.fallback");
}
Authenticator auth = null;
if (!StringUtil.isEmpty(username)) {
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", tls ? "true" : "false");
props.put("mail.smtp.user", username);
props.put("mail.smtp.password", password);
props.put("password", password);
auth = new SMTPAuthenticator(username, password);
} else {
props.put("mail.smtp.auth", "false");
props.remove("mail.smtp.starttls.enable");
props.remove("mail.smtp.user");
props.remove("mail.smtp.password");
props.remove("password");
}
SessionAndTransport sat = newConnection ? new SessionAndTransport(hash(props), props, auth, lifeTimesan, idleTimespan) : SMTPConnectionPool.getSessionAndTransport(props, hash(props), auth, lifeTimesan, idleTimespan);
// Contacts
SMTPMessage msg = new SMTPMessage(sat.session);
if (from == null)
throw new MessagingException("you have do define the from for the mail");
// if(tos==null)throw new MessagingException("you have do define the to for the mail");
checkAddress(from, charset);
// checkAddress(tos,charset);
msg.setFrom(from);
if (tos != null) {
checkAddress(tos, charset);
msg.setRecipients(Message.RecipientType.TO, tos);
}
if (ccs != null) {
checkAddress(ccs, charset);
msg.setRecipients(Message.RecipientType.CC, ccs);
}
if (bccs != null) {
checkAddress(bccs, charset);
msg.setRecipients(Message.RecipientType.BCC, bccs);
}
if (rts != null) {
checkAddress(rts, charset);
msg.setReplyTo(rts);
}
if (fts != null) {
checkAddress(fts, charset);
msg.setEnvelopeFrom(fts[0].toString());
}
// Subject and headers
try {
msg.setSubject(MailUtil.encode(subject, charset.name()));
} catch (UnsupportedEncodingException e) {
throw new MessagingException("the encoding " + charset + " is not supported");
}
msg.setHeader("X-Mailer", xmailer);
msg.setHeader("Date", getNow(timeZone));
Multipart mp = null;
// only Plain
if (StringUtil.isEmpty(htmlText)) {
if (ArrayUtil.isEmpty(attachmentz) && ArrayUtil.isEmpty(parts)) {
fillPlainText(config, msg);
setHeaders(msg, headers);
return new MimeMessageAndSession(msg, sat);
}
mp = new MimeMultipart("mixed");
mp.addBodyPart(getPlainText(config));
} else // Only HTML
if (StringUtil.isEmpty(plainText)) {
if (ArrayUtil.isEmpty(attachmentz) && ArrayUtil.isEmpty(parts)) {
fillHTMLText(config, msg);
setHeaders(msg, headers);
return new MimeMessageAndSession(msg, sat);
}
mp = new MimeMultipart("mixed");
mp.addBodyPart(getHTMLText(config));
} else // Plain and HTML
{
mp = new MimeMultipart("alternative");
mp.addBodyPart(getPlainText(config));
// this need to be last
mp.addBodyPart(getHTMLText(config));
if (!ArrayUtil.isEmpty(attachmentz) || !ArrayUtil.isEmpty(parts)) {
MimeBodyPart content = new MimeBodyPart();
content.setContent(mp);
mp = new MimeMultipart("mixed");
mp.addBodyPart(content);
}
}
// parts
if (!ArrayUtil.isEmpty(parts)) {
Iterator<MailPart> it = parts.iterator();
if (mp instanceof MimeMultipart)
((MimeMultipart) mp).setSubType("alternative");
while (it.hasNext()) {
mp.addBodyPart(toMimeBodyPart(config, it.next()));
}
}
// Attachments
if (!ArrayUtil.isEmpty(attachmentz)) {
for (int i = 0; i < attachmentz.length; i++) {
mp.addBodyPart(toMimeBodyPart(mp, config, attachmentz[i]));
}
}
msg.setContent(mp);
setHeaders(msg, headers);
return new MimeMessageAndSession(msg, sat);
}
use of javax.mail.Multipart in project knime-core by knime.
the class SendMailConfiguration method send.
/**
* Send the mail.
* @throws MessagingException ... when sending fails, also authorization exceptions etc.
* @throws IOException SSL problems or when copying remote URLs to temp local file.
* @throws InvalidSettingsException on invalid referenced flow vars
*/
void send(final FlowVariableProvider flowVarResolver, final CredentialsProvider credProvider) throws MessagingException, IOException, InvalidSettingsException {
String flowVarCorrectedText;
try {
flowVarCorrectedText = FlowVariableResolver.parse(m_text, flowVarResolver);
} catch (NoSuchElementException nse) {
throw new InvalidSettingsException(nse.getMessage(), nse);
}
Properties properties = new Properties(System.getProperties());
String protocol = "smtp";
switch(getConnectionSecurity()) {
case NONE:
break;
case STARTTLS:
properties.setProperty("mail.smtp.starttls.enable", "true");
break;
case SSL:
// this is the way to do it in javax.mail 1.4.5+ (default is currently (Aug '13) 1.4.0):
// www.oracle.com/technetwork/java/javamail145sslnotes-1562622.html
// 'First, and perhaps the simplest, is to set a property to enable use
// of SSL. For example, to enable use of SSL for SMTP connections, set
// the property "mail.smtp.ssl.enable" to "true".'
properties.setProperty("mail.smtp.ssl.enable", "true");
// this is an alternative/backup, which works also:
// http://javakiss.blogspot.ch/2010/10/smtp-in-java-with-javaxmail.html
// I verify it's actually using SSL:
// - it hid a breakpoint in sun.security.ssl.SSLSocketFactoryImpl
// - Hostpoint (knime.com mail server) is rejecting any smtp request on their ssl port (465)
// without this property
properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// a third (and most transparent) option would be to use a different protocol:
protocol = "smtps";
/* note, protocol smptps doesn't work with default javax.mail bundle (1.4.0):
* Unable to load class for provider: protocol=smtps; type=javax.mail.Provider$Type@2d0fc05b;
* class=org.apache.geronimo.javamail.transport.smtp.SMTPTSransport;
* vendor=Apache Software Foundation;version=1.0
* https://issues.apache.org/jira/browse/GERONIMO-4476
* It's a typo in geronimo class name (SMTPSTransport vs. SMTPTSransport) - plenty of google hits.
* (This impl. uses javax.mail.glassfish bundle.) */
break;
default:
}
properties.setProperty("mail." + protocol + ".host", getSmtpHost());
properties.setProperty("mail." + protocol + ".port", Integer.toString(getSmtpPort()));
properties.setProperty("mail." + protocol + ".auth", Boolean.toString(isUseAuthentication()));
Session session = Session.getInstance(properties, null);
MimeMessage message = new MimeMessage(session);
if (!StringUtils.isBlank(getFrom())) {
message.setFrom(new InternetAddress(getFrom()));
} else {
message.setFrom();
}
if (!StringUtils.isBlank(getTo())) {
message.addRecipients(Message.RecipientType.TO, parseAndValidateRecipients(getTo()));
}
if (!StringUtils.isBlank(getCc())) {
message.addRecipients(Message.RecipientType.CC, parseAndValidateRecipients(getCc()));
}
if (!StringUtils.isBlank(getBcc())) {
message.addRecipients(Message.RecipientType.BCC, parseAndValidateRecipients(getBcc()));
}
if (message.getAllRecipients() == null) {
throw new InvalidSettingsException("No recipients specified");
}
message.setHeader("X-Mailer", "KNIME/" + KNIMEConstants.VERSION);
message.setHeader("X-Priority", m_priority.toXPriority());
message.setSentDate(new Date());
message.setSubject(getSubject());
// text or html message part
MimeBodyPart contentBody = new MimeBodyPart();
String textType;
switch(getFormat()) {
case Html:
textType = "text/html; charset=\"utf-8\"";
break;
case Text:
textType = "text/plain; charset=\"utf-8\"";
break;
default:
throw new RuntimeException("Unsupported format: " + getFormat());
}
contentBody.setContent(flowVarCorrectedText, textType);
Multipart mp = new MimeMultipart();
mp.addBodyPart(contentBody);
List<File> tempDirs = new ArrayList<File>();
Transport t = null;
ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader();
// make sure to set class loader to javax.mail - this has caused problems in the past, see bug 5316
Thread.currentThread().setContextClassLoader(Session.class.getClassLoader());
try {
for (URL url : getAttachedURLs()) {
MimeBodyPart filePart = new MimeBodyPart();
File file;
if ("file".equals(url.getProtocol())) {
try {
file = new File(url.toURI());
} catch (URISyntaxException e) {
throw new IOException("Invalid attachment: " + url, e);
}
} else {
File tempDir = FileUtil.createTempDir("send-mail-attachment");
tempDirs.add(tempDir);
try {
file = new File(tempDir, FilenameUtils.getName(url.toURI().getSchemeSpecificPart()));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
FileUtils.copyURLToFile(url, file);
}
if (!file.canRead()) {
throw new IOException("Unable to file attachment \"" + url + "\"");
}
filePart.attachFile(file);
// java 7u7 is missing mimemtypes.default file:
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7096063
// find mime type in this bundle (META-INF folder contains mime.types) and set it
filePart.setHeader("Content-Type", FileTypeMap.getDefaultFileTypeMap().getContentType(file));
mp.addBodyPart(filePart);
}
t = session.getTransport(protocol);
if (isUseAuthentication()) {
String user;
String pass;
if (isUseCredentials()) {
ICredentials iCredentials = credProvider.get(getCredentialsId());
user = iCredentials.getLogin();
pass = iCredentials.getPassword();
} else {
user = getSmtpUser();
pass = getSmtpPassword();
}
t.connect(user, pass);
} else {
t.connect();
}
message.setContent(mp);
t.sendMessage(message, message.getAllRecipients());
} finally {
Thread.currentThread().setContextClassLoader(oldContextClassLoader);
for (File d : tempDirs) {
FileUtils.deleteQuietly(d);
}
if (t != null) {
t.close();
}
}
}
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 wombat by PLOS.
the class FeedbackController method receiveFeedback.
@RequestMapping(name = "feedbackPost", value = "/feedback", method = RequestMethod.POST)
public String receiveFeedback(HttpServletRequest request, HttpServletResponse response, Model model, @SiteParam Site site, @RequestParam("fromEmailAddress") String fromEmailAddress, @RequestParam("note") String note, @RequestParam("subject") String subject, @RequestParam("name") String name, @RequestParam("userId") String userId, @RequestParam(value = "authorPhone", required = false) String authorPhone, @RequestParam(value = "authorAffiliation", required = false) String authorAffiliation) throws IOException, MessagingException {
validateFeedbackConfig(site);
// Fill input parameters into model. (These can be used in two ways: in the generated email if all input is valid,
// or in the form in case we need to display validation errors.)
model.addAttribute("fromEmailAddress", fromEmailAddress);
model.addAttribute("note", note);
model.addAttribute("name", name);
model.addAttribute("subject", subject);
Set<String> errors = validateInput(fromEmailAddress, note, subject, name);
if (applyValidation(response, model, errors)) {
return serveFeedbackPage(model, site);
}
if (subject.isEmpty()) {
model.addAttribute("subject", getFeedbackConfig(site).get("defaultSubject"));
}
model.addAttribute("id", userId);
model.addAttribute("userInfo", formatUserInfo(request));
if (honeypotService.checkHoneypot(request, authorPhone, authorAffiliation)) {
return site + "/ftl/feedback/success";
}
Multipart content = freemarkerMailService.createContent(site, "feedback", model);
String destinationAddress = (String) getFeedbackConfig(site).get("destination");
EmailMessage message = EmailMessage.builder().addToEmailAddress(EmailMessage.createAddress(null, destinationAddress)).setSenderAddress(EmailMessage.createAddress(name, fromEmailAddress)).setSubject(subject).setContent(content).setEncoding(freeMarkerConfig.getConfiguration().getDefaultEncoding()).build();
message.send(javaMailSender);
return site + "/ftl/feedback/success";
}
Aggregations