List of usage examples for javax.mail BodyPart setText
public void setText(String text) throws MessagingException;
From source file:com.zacwolf.commons.email.Email.java
public Multipart getAsMultipart() throws MessagingException { /** First we create the "related" htmlmultipart for the html email content: * ?/*w ww . jav a 2 s.c om*/ * msg.setContent() * ? * htmlmultipart [MimeMultipart("related")] * ? * htmlmessageBodyPart [MimeBodyPart] * * EmailAttachment(INLINE) [MimeBodyPart] * * EmailAttachment(INLINE) [BodyPart] * * * **/ final Multipart htmlmultipart = new MimeMultipart("related"); final BodyPart htmlmessageBodyPart = new MimeBodyPart(); htmlmultipart.addBodyPart(htmlmessageBodyPart); final org.jsoup.nodes.Document doc = Jsoup.parse(getBody(), "UTF-8"); prepareImgs(doc, htmlmultipart); prepare(doc); htmlmessageBodyPart.setContent(doc.toString(), "text/html; charset=utf-8"); // populate the top multipart Multipart msgmultipart = htmlmultipart; if (getBodyPlainText() != null) {// Now create a plain-text body part /** * If there is a plain text attachment (and their should always be one), * then an "alternative" type MimeMultipart is added to the structure * ? * msg.setContent() * ? * msgmultipart [MimeMultipart("alternative")] * ? * htmlcontent [MimeBodyPart] * ? * htmlmultipart [MimeMultipart("related")] * ? * htmlmessageBodyPart [MimeBodyPart] * * EmailAttachment(INLINE) [MimeBodyPart] * * EmailAttachment(INLINE) [MimeBodyPart] * * * * plaintxtBodypart [MimeBodyPart] * .setText(message_plaintxt) * * * */ msgmultipart = new MimeMultipart("alternative"); final BodyPart plaintxtBodyPart = new MimeBodyPart(); plaintxtBodyPart.setText(getBodyPlainText()); final BodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(htmlmultipart); msgmultipart.addBodyPart(plaintxtBodyPart); msgmultipart.addBodyPart(htmlBodyPart); } /** * If there are non-inline attachments, then a "mixed" type * MimeMultipart object has to be added to the structure * ? * msg.setContent() * ? * msgmultipart [MimeMultipart("mixed")] * ? * wrap [MimeBodyPart] * ? * msgmultipart [MimeMultipart("alternative")] * ? * htmlcontent [MimeBodyPart] * ? * htmlmultipart [MimeMultipart("related")] * ? * htmlmessageBodyPart [MimeBodyPart] * * EmailAttachment(INLINE) [MimeBodyPart] * * EmailAttachment(INLINE) [MimeBodyPart] * * * * plaintxtBodypart [MimeBodyPart] * .setText(message_plaintxt) * * * * EmailAttachment (non-inline) [MimeBodyPart] * * EmailAttachment (non-inline) [MimeBodyPart] * * * */ Multipart mixed = msgmultipart; final Set<EmailAttachment> noninlineattachments = new HashSet<EmailAttachment>(); for (EmailAttachment attach : getAttachments().values()) if (attach.disposition != null && !attach.disposition.equals(MimeBodyPart.INLINE)) noninlineattachments.add(attach); // If there are non-IN-LINE attachments, we'll have to create another layer "mixed" MultiPart object if (!noninlineattachments.isEmpty()) { mixed = new MimeMultipart("mixed"); //Multiparts are not themselves containers, so create a wrapper BodyPart container final BodyPart wrap = new MimeBodyPart(); wrap.setContent(msgmultipart); mixed.addBodyPart(wrap); for (EmailAttachment attach : noninlineattachments) mixed.addBodyPart(attach); } return mixed; }
From source file:com.nridge.core.app.mail.MailManager.java
/** * If the property "delivery_enabled" is <i>true</i>, then this method * will generate an email message that includes subject, message and * attachments to the recipient list. You can use the convenience * methods <i>lookupFromAddress()</i>, <i>createRecipientList()</i> * and <i>createAttachmentList()</i> for parameter building assistance. * * @param aFromAddress Source email address. * @param aRecipientList List of recipient email addresses. * @param aSubject Subject of the email message. * @param aMessage Messsage./*from www . ja v a 2s . c o m*/ * @param anAttachmentFiles List of file attachments or <i>null</i> for none. * * @see <a href="https://www.tutorialspoint.com/javamail_api/javamail_api_send_email_with_attachment.htm">JavaMail API Attachments</a> * @see <a href="https://stackoverflow.com/questions/6756162/how-do-i-send-mail-with-both-plain-text-as-well-as-html-text-so-that-each-mail-r">JavaMail API MIME Types</a> * * @throws IOException I/O related error condition. * @throws NSException Missing configuration properties. * @throws MessagingException Message subsystem error condition. */ public void sendMessage(String aFromAddress, ArrayList<String> aRecipientList, String aSubject, String aMessage, ArrayList<String> anAttachmentFiles) throws IOException, NSException, MessagingException { InternetAddress internetAddressFrom, internetAddressTo; Logger appLogger = mAppMgr.getLogger(this, "sendMessage"); appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER); if (isCfgStringTrue("delivery_enabled")) { if ((StringUtils.isNotEmpty(aFromAddress)) && (aRecipientList.size() > 0) && (StringUtils.isNotEmpty(aSubject)) && (StringUtils.isNotEmpty(aMessage))) { initialize(); Message mimeMessage = new MimeMessage(mMailSession); internetAddressFrom = new InternetAddress(aFromAddress); mimeMessage.addFrom(new InternetAddress[] { internetAddressFrom }); for (String mailAddressTo : aRecipientList) { internetAddressTo = new InternetAddress(mailAddressTo); mimeMessage.addRecipient(MimeMessage.RecipientType.TO, internetAddressTo); } mimeMessage.setSubject(aSubject); // The following logic create a multi-part message and adds the attachment to it. BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(aMessage); // messageBodyPart.setContent(aMessage, "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); if ((anAttachmentFiles != null) && (anAttachmentFiles.size() > 0)) { for (String pathFileName : anAttachmentFiles) { File attachmentFile = new File(pathFileName); if (attachmentFile.exists()) { messageBodyPart = new MimeBodyPart(); DataSource fileDataSource = new FileDataSource(pathFileName); messageBodyPart.setDataHandler(new DataHandler(fileDataSource)); messageBodyPart.setFileName(attachmentFile.getName()); multipart.addBodyPart(messageBodyPart); } } appLogger.debug(String.format("Mail Message (%s): %s - with attachments", aSubject, aMessage)); } else appLogger.debug(String.format("Mail Message (%s): %s", aSubject, aMessage)); mimeMessage.setContent(multipart); Transport.send(mimeMessage); } else throw new NSException("Valid from, recipient, subject and message are required parameters."); } else appLogger.warn("Email delivery is not enabled - no message will be sent."); appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART); }
From source file:com.duroty.utils.mail.MessageUtilities.java
/** * DOCUMENT ME!/* w ww. j a v a 2 s.c om*/ * * @param from DOCUMENT ME! * @param to DOCUMENT ME! * @param subjectPrefix DOCUMENT ME! * @param subjectSuffix DOCUMENT ME! * @param msgText DOCUMENT ME! * @param message DOCUMENT ME! * @param session DOCUMENT ME! * * @return DOCUMENT ME! * * @throws Exception DOCUMENT ME! * @throws IllegalArgumentException DOCUMENT ME! */ public static MimeMessage createNewMessage(Address from, Address[] to, String subjectPrefix, String subjectSuffix, String msgText, MimeMessage message, Session session) throws Exception { if (from == null) { throw new IllegalArgumentException("from addres cannot be null."); } if ((to == null) || (to.length <= 0)) { throw new IllegalArgumentException("to addres cannot be null."); } if (message == null) { throw new IllegalArgumentException("to message cannot be null."); } try { //Create the message MimeMessage newMessage = new MimeMessage(session); StringBuffer buffer = new StringBuffer(); if (subjectPrefix != null) { buffer.append(subjectPrefix); } if (message.getSubject() != null) { buffer.append(message.getSubject()); } if (subjectSuffix != null) { buffer.append(subjectSuffix); } if (buffer.length() > 0) { newMessage.setSubject(buffer.toString()); } newMessage.setFrom(from); newMessage.addRecipients(Message.RecipientType.TO, to); //Create your new message part BodyPart messageBodyPart1 = new MimeBodyPart(); messageBodyPart1.setText(msgText); //Create a multi-part to combine the parts Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart1); //Create and fill part for the forwarded content BodyPart messageBodyPart2 = new MimeBodyPart(); messageBodyPart2.setDataHandler(message.getDataHandler()); //Add part to multi part multipart.addBodyPart(messageBodyPart2); //Associate multi-part with message newMessage.setContent(multipart); newMessage.saveChanges(); return newMessage; } finally { } }
From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java
/** * Creates a Multipart MIME Message (multiple content-types within the same message) from an existing mail * //ww w . j a v a2s . c om * @param mail The original Mail * @return The Multipart MIME message */ public Multipart createMimeMultipart(Mail mail, XWikiContext context) throws MessagingException, XWikiException, IOException { Multipart multipart; List<Attachment> rawAttachments = mail.getAttachments() != null ? mail.getAttachments() : new ArrayList<Attachment>(); if (mail.getHtmlPart() == null && mail.getAttachments() != null) { multipart = new MimeMultipart("mixed"); // Create the text part of the email BodyPart textPart = new MimeBodyPart(); textPart.setContent(mail.getTextPart(), "text/plain; charset=" + EMAIL_ENCODING); multipart.addBodyPart(textPart); // Add attachments to the main multipart for (Attachment attachment : rawAttachments) { multipart.addBodyPart(createAttachmentBodyPart(attachment, context)); } } else { multipart = new MimeMultipart("mixed"); List<Attachment> attachments = new ArrayList<Attachment>(); List<Attachment> embeddedImages = new ArrayList<Attachment>(); // Create the text part of the email BodyPart textPart; textPart = new MimeBodyPart(); textPart.setText(mail.getTextPart()); // Create the HTML part of the email, define the html as a multipart/related in case there are images Multipart htmlMultipart = new MimeMultipart("related"); BodyPart htmlPart = new MimeBodyPart(); htmlPart.setContent(mail.getHtmlPart(), "text/html; charset=" + EMAIL_ENCODING); htmlPart.setHeader("Content-Disposition", "inline"); htmlPart.setHeader("Content-Transfer-Encoding", "quoted-printable"); htmlMultipart.addBodyPart(htmlPart); // Find images used with src="cid:" in the email HTML part Pattern cidPattern = Pattern.compile("src=('|\")cid:([^'\"]*)('|\")", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); Matcher matcher = cidPattern.matcher(mail.getHtmlPart()); List<String> foundEmbeddedImages = new ArrayList<String>(); while (matcher.find()) { foundEmbeddedImages.add(matcher.group(2)); } // Loop over the attachments of the email, add images used from the HTML to the list of attachments to be // embedded with the HTML part, add the other attachements to the list of attachments to be attached to the // email. for (Attachment attachment : rawAttachments) { if (foundEmbeddedImages.contains(attachment.getFilename())) { embeddedImages.add(attachment); } else { attachments.add(attachment); } } // Add the images to the HTML multipart (they should be hidden from the mail reader attachment list) for (Attachment image : embeddedImages) { htmlMultipart.addBodyPart(createAttachmentBodyPart(image, context)); } // Wrap the HTML and text parts in an alternative body part and add it to the main multipart Multipart alternativePart = new MimeMultipart("alternative"); BodyPart alternativeMultipartWrapper = new MimeBodyPart(); BodyPart htmlMultipartWrapper = new MimeBodyPart(); alternativePart.addBodyPart(textPart); htmlMultipartWrapper.setContent(htmlMultipart); alternativePart.addBodyPart(htmlMultipartWrapper); alternativeMultipartWrapper.setContent(alternativePart); multipart.addBodyPart(alternativeMultipartWrapper); // Add attachments to the main multipart for (Attachment attachment : attachments) { multipart.addBodyPart(createAttachmentBodyPart(attachment, context)); } } return multipart; }
From source file:nl.nn.adapterframework.senders.MailSender.java
protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType, String messageBase64, String charset, Collection recipients, Collection attachments) throws SenderException { StringBuffer sb = new StringBuffer(); if (recipients == null || recipients.size() == 0) { throw new SenderException("MailSender [" + getName() + "] has no recipients for message"); }//from w w w.j a v a2 s . c o m if (StringUtils.isEmpty(from)) { from = defaultFrom; } if (StringUtils.isEmpty(subject)) { subject = defaultSubject; } log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject + "] to #recipients [" + recipients.size() + "]"); if (StringUtils.isEmpty(messageType)) { messageType = defaultMessageType; } if (StringUtils.isEmpty(messageBase64)) { messageBase64 = defaultMessageBase64; } try { if (log.isDebugEnabled()) { sb.append("MailSender [" + getName() + "] sending message "); sb.append("[smtpHost=" + smtpHost); sb.append("[from=" + from + "]"); sb.append("[subject=" + subject + "]"); sb.append("[threadTopic=" + threadTopic + "]"); sb.append("[text=" + message + "]"); sb.append("[type=" + messageType + "]"); sb.append("[base64=" + messageBase64 + "]"); } if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) { message = decodeBase64ToString(message); } // construct a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setSubject(subject, charset); if (StringUtils.isNotEmpty(threadTopic)) { msg.setHeader("Thread-Topic", threadTopic); } Iterator iter = recipients.iterator(); boolean recipientsFound = false; while (iter.hasNext()) { Element recipientElement = (Element) iter.next(); String recipient = XmlUtils.getStringValue(recipientElement); if (StringUtils.isNotEmpty(recipient)) { String typeAttr = recipientElement.getAttribute("type"); Message.RecipientType recipientType = Message.RecipientType.TO; if ("cc".equalsIgnoreCase(typeAttr)) { recipientType = Message.RecipientType.CC; } if ("bcc".equalsIgnoreCase(typeAttr)) { recipientType = Message.RecipientType.BCC; } msg.addRecipient(recipientType, new InternetAddress(recipient)); recipientsFound = true; if (log.isDebugEnabled()) { sb.append("[recipient(" + typeAttr + ")=" + recipient + "]"); } } else { log.debug("empty recipient found, ignoring"); } } if (!recipientsFound) { throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients"); } String messageTypeWithCharset; if (charset == null) { charset = System.getProperty("mail.mime.charset"); if (charset == null) { charset = System.getProperty("file.encoding"); } } if (charset != null) { messageTypeWithCharset = messageType + ";charset=" + charset; } else { messageTypeWithCharset = messageType; } log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]"); if (attachments == null || attachments.size() == 0) { //msg.setContent(message, messageType); msg.setContent(message, messageTypeWithCharset); } else { Multipart multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); //messageBodyPart.setContent(message, messageType); messageBodyPart.setContent(message, messageTypeWithCharset); multipart.addBodyPart(messageBodyPart); iter = attachments.iterator(); while (iter.hasNext()) { Element attachmentElement = (Element) iter.next(); String attachmentText = XmlUtils.getStringValue(attachmentElement); String attachmentName = attachmentElement.getAttribute("name"); String attachmentUrl = attachmentElement.getAttribute("url"); String attachmentType = attachmentElement.getAttribute("type"); String attachmentBase64 = attachmentElement.getAttribute("base64"); if (StringUtils.isEmpty(attachmentType)) { attachmentType = getDefaultAttachmentType(); } if (StringUtils.isEmpty(attachmentName)) { attachmentName = getDefaultAttachmentName(); } log.debug("found attachment [" + attachmentName + "] type [" + attachmentType + "] url [" + attachmentUrl + "]contents [" + attachmentText + "]"); messageBodyPart = new MimeBodyPart(); DataSource attachmentDataSource; if (!StringUtils.isEmpty(attachmentUrl)) { attachmentDataSource = new URLDataSource(new URL(attachmentUrl)); messageBodyPart.setDataHandler(new DataHandler(attachmentDataSource)); } messageBodyPart.setFileName(attachmentName); if ("true".equalsIgnoreCase(attachmentBase64)) { messageBodyPart.setDataHandler(decodeBase64(attachmentText)); } else { messageBodyPart.setText(attachmentText); } multipart.addBodyPart(messageBodyPart); } msg.setContent(multipart); } log.debug(sb.toString()); msg.setSentDate(new Date()); msg.saveChanges(); // send the message putOnTransport(msg); // return the mail in mail-safe from ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); byte[] byteArray = out.toByteArray(); return Misc.byteArrayToString(byteArray, "\n", false); } catch (Exception e) { throw new SenderException("MailSender got error", e); } }
From source file:nl.nn.adapterframework.senders.MailSenderOld.java
protected String sendEmail(String from, String subject, String threadTopic, String message, String messageType, String messageBase64, String charset, Collection<Recipient> recipients, Collection<Attachment> attachments) throws SenderException { StringBuffer sb = new StringBuffer(); if (recipients == null || recipients.size() == 0) { throw new SenderException("MailSender [" + getName() + "] has no recipients for message"); }//from w ww . j a va2s. c o m if (StringUtils.isEmpty(from)) { from = defaultFrom; } if (StringUtils.isEmpty(subject)) { subject = defaultSubject; } log.debug("MailSender [" + getName() + "] requested to send message from [" + from + "] subject [" + subject + "] to #recipients [" + recipients.size() + "]"); if (StringUtils.isEmpty(messageType)) { messageType = defaultMessageType; } if (StringUtils.isEmpty(messageBase64)) { messageBase64 = defaultMessageBase64; } try { if (log.isDebugEnabled()) { sb.append("MailSender [" + getName() + "] sending message "); sb.append("[smtpHost=" + smtpHost); sb.append("[from=" + from + "]"); sb.append("[subject=" + subject + "]"); sb.append("[threadTopic=" + threadTopic + "]"); sb.append("[text=" + message + "]"); sb.append("[type=" + messageType + "]"); sb.append("[base64=" + messageBase64 + "]"); } if ("true".equalsIgnoreCase(messageBase64) && StringUtils.isNotEmpty(message)) { message = decodeBase64ToString(message); } // construct a message MimeMessage msg = new MimeMessage(session); msg.setFrom(new InternetAddress(from)); msg.setSubject(subject, charset); if (StringUtils.isNotEmpty(threadTopic)) { msg.setHeader("Thread-Topic", threadTopic); } Iterator iter = recipients.iterator(); boolean recipientsFound = false; while (iter.hasNext()) { Recipient recipient = (Recipient) iter.next(); String value = recipient.value; String type = recipient.type; Message.RecipientType recipientType; if ("cc".equalsIgnoreCase(type)) { recipientType = Message.RecipientType.CC; } else if ("bcc".equalsIgnoreCase(type)) { recipientType = Message.RecipientType.BCC; } else { recipientType = Message.RecipientType.TO; } msg.addRecipient(recipientType, new InternetAddress(value)); recipientsFound = true; if (log.isDebugEnabled()) { sb.append("[recipient [" + recipient + "]]"); } } if (!recipientsFound) { throw new SenderException("MailSender [" + getName() + "] did not find any valid recipients"); } String messageTypeWithCharset; if (charset == null) { charset = System.getProperty("mail.mime.charset"); if (charset == null) { charset = System.getProperty("file.encoding"); } } if (charset != null) { messageTypeWithCharset = messageType + ";charset=" + charset; } else { messageTypeWithCharset = messageType; } log.debug("MailSender [" + getName() + "] uses encoding [" + messageTypeWithCharset + "]"); if (attachments == null || attachments.size() == 0) { //msg.setContent(message, messageType); msg.setContent(message, messageTypeWithCharset); } else { Multipart multipart = new MimeMultipart(); BodyPart messageBodyPart = new MimeBodyPart(); //messageBodyPart.setContent(message, messageType); messageBodyPart.setContent(message, messageTypeWithCharset); multipart.addBodyPart(messageBodyPart); int counter = 0; iter = attachments.iterator(); while (iter.hasNext()) { counter++; Attachment attachment = (Attachment) iter.next(); Object value = attachment.getValue(); String name = attachment.getName(); if (StringUtils.isEmpty(name)) { name = getDefaultAttachmentName() + counter; } log.debug("found attachment [" + attachment + "]"); messageBodyPart = new MimeBodyPart(); messageBodyPart.setFileName(name); if (value instanceof DataHandler) { messageBodyPart.setDataHandler((DataHandler) value); } else { messageBodyPart.setText((String) value); } multipart.addBodyPart(messageBodyPart); } msg.setContent(multipart); } log.debug(sb.toString()); msg.setSentDate(new Date()); msg.saveChanges(); // send the message putOnTransport(msg); // return the mail in mail-safe from ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); byte[] byteArray = out.toByteArray(); return Misc.byteArrayToString(byteArray, "\n", false); } catch (Exception e) { throw new SenderException("MailSender got error", e); } }
From source file:org.alfresco.tutorial.repoaction.SendAsEmailActionExecuter.java
@Override protected void executeImpl(Action action, NodeRef actionedUponNodeRef) { if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == true) { // Get the email properties entered via Share Form String to = (String) action.getParameterValue(PARAM_EMAIL_TO_NAME); String subject = (String) action.getParameterValue(PARAM_EMAIL_SUBJECT_NAME); String body = (String) action.getParameterValue(PARAM_EMAIL_BODY_NAME); // Get document filename Serializable filename = serviceRegistry.getNodeService().getProperty(actionedUponNodeRef, ContentModel.PROP_NAME); if (filename == null) { throw new AlfrescoRuntimeException("Document filename is null"); }//from ww w .j a va 2 s. co m String documentName = (String) filename; try { // Create mail session Properties mailServerProperties = new Properties(); mailServerProperties = System.getProperties(); mailServerProperties.put("mail.smtp.host", "localhost"); mailServerProperties.put("mail.smtp.port", "2525"); Session session = Session.getDefaultInstance(mailServerProperties, null); session.setDebug(false); // Define message Message message = new MimeMessage(session); String fromAddress = "training@alfresco.com"; message.setFrom(new InternetAddress(fromAddress)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject(subject); // Create the message part with body text BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Create the Attachment part // // Get the document content bytes byte[] documentData = getDocumentContentBytes(actionedUponNodeRef, documentName); if (documentData == null) { throw new AlfrescoRuntimeException("Document content is null"); } // Attach document messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(new ByteArrayDataSource(documentData, new MimetypesFileTypeMap().getContentType(documentName)))); messageBodyPart.setFileName(documentName); multipart.addBodyPart(messageBodyPart); // Put parts in message message.setContent(multipart); // Send mail Transport.send(message); // Set status on node as "sent via email" Map<QName, Serializable> properties = new HashMap<QName, Serializable>(); properties.put(ContentModel.PROP_ORIGINATOR, fromAddress); properties.put(ContentModel.PROP_ADDRESSEE, to); properties.put(ContentModel.PROP_SUBJECT, subject); properties.put(ContentModel.PROP_SENTDATE, new Date()); serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, ContentModel.ASPECT_EMAILED, properties); } catch (MessagingException me) { me.printStackTrace(); throw new AlfrescoRuntimeException("Could not send email: " + me.getMessage()); } } }
From source file:org.apache.axis2.transport.mail.EMailSender.java
private void createMailMimeMessage(final MimeMessage msg, MailToInfo mailToInfo, OMOutputFormat format) throws MessagingException { // Create the message part BodyPart messageBodyPart = new MimeBase64BodyPart(); messageBodyPart.setText(""); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); DataSource source = null;//from ww w . j a v a 2s.c o m // Part two is attachment if (outputStream instanceof ByteArrayOutputStream) { source = new ByteArrayDataSource(((ByteArrayOutputStream) outputStream).toByteArray()); } messageBodyPart = new MimeBase64BodyPart(); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setDisposition(Part.ATTACHMENT); messageBodyPart.addHeader("Content-Description", "\"" + mailToInfo.getContentDescription() + "\""); String contentType = format.getContentType() != null ? format.getContentType() : Constants.DEFAULT_CONTENT_TYPE; if (contentType.indexOf(SOAP11Constants.SOAP_11_CONTENT_TYPE) > -1) { if (messageContext.getSoapAction() != null) { messageBodyPart.setHeader(Constants.HEADER_SOAP_ACTION, messageContext.getSoapAction()); } } if (contentType.indexOf(SOAP12Constants.SOAP_12_CONTENT_TYPE) > -1) { if (messageContext.getSoapAction() != null) { messageBodyPart.setHeader("Content-Type", contentType + "; charset=" + format.getCharSetEncoding() + " ; action=\"" + messageContext.getSoapAction() + "\""); } } else { messageBodyPart.setHeader("Content-Type", contentType + "; charset=" + format.getCharSetEncoding()); } multipart.addBodyPart(messageBodyPart); msg.setContent(multipart); }
From source file:org.apache.jmeter.protocol.smtp.sampler.protocol.SendMailCommand.java
/** * Prepares message prior to be sent via execute()-method, i.e. sets * properties such as protocol, authentication, etc. * * @return Message-object to be sent to execute()-method * @throws MessagingException/*from www .j a v a2 s.co m*/ * when problems constructing or sending the mail occur * @throws IOException * when the mail content can not be read or truststore problems * are detected */ public Message prepareMessage() throws MessagingException, IOException { Properties props = new Properties(); String protocol = getProtocol(); // set properties using JAF props.setProperty("mail." + protocol + ".host", smtpServer); props.setProperty("mail." + protocol + ".port", getPort()); props.setProperty("mail." + protocol + ".auth", Boolean.toString(useAuthentication)); // set timeout props.setProperty("mail." + protocol + ".timeout", getTimeout()); props.setProperty("mail." + protocol + ".connectiontimeout", getConnectionTimeout()); if (useStartTLS || useSSL) { try { String allProtocols = StringUtils .join(SSLContext.getDefault().getSupportedSSLParameters().getProtocols(), " "); logger.info("Use ssl/tls protocols for mail: " + allProtocols); props.setProperty("mail." + protocol + ".ssl.protocols", allProtocols); } catch (Exception e) { logger.error("Problem setting ssl/tls protocols for mail", e); } } if (enableDebug) { props.setProperty("mail.debug", "true"); } if (useStartTLS) { props.setProperty("mail.smtp.starttls.enable", "true"); if (enforceStartTLS) { // Requires JavaMail 1.4.2+ props.setProperty("mail.smtp.starttls.require", "true"); } } if (trustAllCerts) { if (useSSL) { props.setProperty("mail.smtps.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY); props.setProperty("mail.smtps.ssl.socketFactory.fallback", "false"); } else if (useStartTLS) { props.setProperty("mail.smtp.ssl.socketFactory.class", TRUST_ALL_SOCKET_FACTORY); props.setProperty("mail.smtp.ssl.socketFactory.fallback", "false"); } } else if (useLocalTrustStore) { File truststore = new File(trustStoreToUse); logger.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath()); if (!truststore.exists()) { logger.info( "load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath()); truststore = new File(FileServer.getFileServer().getBaseDir(), trustStoreToUse); logger.info("load local truststore -Attempting to read truststore from: " + truststore.getAbsolutePath()); if (!truststore.exists()) { logger.info( "load local truststore -Failed to load truststore from: " + truststore.getAbsolutePath() + ". Local truststore not available, aborting execution."); throw new IOException("Local truststore file not found. Also not available under : " + truststore.getAbsolutePath()); } } if (useSSL) { // Requires JavaMail 1.4.2+ props.put("mail.smtps.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore)); props.put("mail.smtps.ssl.socketFactory.fallback", "false"); } else if (useStartTLS) { // Requires JavaMail 1.4.2+ props.put("mail.smtp.ssl.socketFactory", new LocalTrustStoreSSLSocketFactory(truststore)); props.put("mail.smtp.ssl.socketFactory.fallback", "false"); } } session = Session.getInstance(props, null); Message message; if (sendEmlMessage) { message = new MimeMessage(session, new BufferedInputStream(new FileInputStream(emlMessage))); } else { message = new MimeMessage(session); // handle body and attachments Multipart multipart = new MimeMultipart(); final int attachmentCount = attachments.size(); if (plainBody && (attachmentCount == 0 || (mailBody.length() == 0 && attachmentCount == 1))) { if (attachmentCount == 1) { // i.e. mailBody is empty File first = attachments.get(0); InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(first)); message.setText(IOUtils.toString(is)); } finally { IOUtils.closeQuietly(is); } } else { message.setText(mailBody); } } else { BodyPart body = new MimeBodyPart(); body.setText(mailBody); multipart.addBodyPart(body); for (File f : attachments) { BodyPart attach = new MimeBodyPart(); attach.setFileName(f.getName()); attach.setDataHandler(new DataHandler(new FileDataSource(f.getAbsolutePath()))); multipart.addBodyPart(attach); } message.setContent(multipart); } } // set from field and subject if (null != sender) { message.setFrom(new InternetAddress(sender)); } if (null != replyTo) { InternetAddress[] to = new InternetAddress[replyTo.size()]; message.setReplyTo(replyTo.toArray(to)); } if (null != subject) { message.setSubject(subject); } if (receiverTo != null) { InternetAddress[] to = new InternetAddress[receiverTo.size()]; receiverTo.toArray(to); message.setRecipients(Message.RecipientType.TO, to); } if (receiverCC != null) { InternetAddress[] cc = new InternetAddress[receiverCC.size()]; receiverCC.toArray(cc); message.setRecipients(Message.RecipientType.CC, cc); } if (receiverBCC != null) { InternetAddress[] bcc = new InternetAddress[receiverBCC.size()]; receiverBCC.toArray(bcc); message.setRecipients(Message.RecipientType.BCC, bcc); } for (int i = 0; i < headerFields.size(); i++) { Argument argument = (Argument) ((TestElementProperty) headerFields.get(i)).getObjectValue(); message.setHeader(argument.getName(), argument.getValue()); } message.saveChanges(); return message; }
From source file:org.apache.mailet.base.test.MimeMessageBuilder.java
public MimeMessage build() throws MessagingException { Preconditions.checkState(!(text.isPresent() && content.isPresent()), "Can not get at the same time a text and a content"); MimeMessage mimeMessage = new MimeMessage(Session.getInstance(new Properties())); if (text.isPresent()) { BodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(text.get()); mimeMessage.setContent(bodyPart, "text/plain"); }/*from w w w . j av a 2 s . c o m*/ if (content.isPresent()) { mimeMessage.setContent(content.get()); } if (sender.isPresent()) { mimeMessage.setSender(sender.get()); } if (from.isPresent()) { mimeMessage.setFrom(from.get()); } if (subject.isPresent()) { mimeMessage.setSubject(subject.get()); } List<InternetAddress> toAddresses = to.build(); if (!toAddresses.isEmpty()) { mimeMessage.setRecipients(Message.RecipientType.TO, toAddresses.toArray(new InternetAddress[toAddresses.size()])); } List<InternetAddress> ccAddresses = cc.build(); if (!ccAddresses.isEmpty()) { mimeMessage.setRecipients(Message.RecipientType.CC, ccAddresses.toArray(new InternetAddress[ccAddresses.size()])); } List<InternetAddress> bccAddresses = bcc.build(); if (!bccAddresses.isEmpty()) { mimeMessage.setRecipients(Message.RecipientType.BCC, bccAddresses.toArray(new InternetAddress[bccAddresses.size()])); } List<Header> headerList = headers.build(); for (Header header : headerList) { mimeMessage.addHeader(header.name, header.value); } mimeMessage.saveChanges(); return mimeMessage; }