List of usage examples for javax.mail.internet MimeBodyPart setHeader
@Override public void setHeader(String name, String value) throws MessagingException
From source file:com.intuit.tank.mail.TankMailer.java
/** * @{inheritDoc// w ww .j a v a 2 s. c o m */ @Override public void sendMail(MailMessage message, String... emailAddresses) { MailConfig mailConfig = new TankConfig().getMailConfig(); Properties props = new Properties(); props.put("mail.smtp.host", mailConfig.getSmtpHost()); props.put("mail.smtp.port", mailConfig.getSmtpPort()); Session mailSession = Session.getDefaultInstance(props); Message simpleMessage = new MimeMessage(mailSession); InternetAddress fromAddress = null; InternetAddress toAddress = null; try { fromAddress = new InternetAddress(mailConfig.getMailFrom()); simpleMessage.setFrom(fromAddress); for (String email : emailAddresses) { try { toAddress = new InternetAddress(email); simpleMessage.addRecipient(RecipientType.TO, toAddress); } catch (AddressException e) { LOG.warn("Error with recipient " + email + ": " + e.toString()); } } simpleMessage.setSubject(message.getSubject()); final MimeBodyPart textPart = new MimeBodyPart(); textPart.setContent(message.getPlainTextBody(), "text/plain"); textPart.setHeader("MIME-Version", "1.0"); textPart.setHeader("Content-Type", textPart.getContentType()); // HTML version final MimeBodyPart htmlPart = new MimeBodyPart(); // htmlPart.setContent(message.getHtmlBody(), "text/html"); htmlPart.setDataHandler(new DataHandler(new HTMLDataSource(message.getHtmlBody()))); htmlPart.setHeader("MIME-Version", "1.0"); htmlPart.setHeader("Content-Type", "text/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 simpleMessage.setContent(mp); simpleMessage.setHeader("MIME-Version", "1.0"); simpleMessage.setHeader("Content-Type", mp.getContentType()); logMsg(mailConfig.getSmtpHost(), simpleMessage); if (simpleMessage.getRecipients(RecipientType.TO) != null && simpleMessage.getRecipients(RecipientType.TO).length > 0) { Transport.send(simpleMessage); } } catch (MessagingException e) { throw new RuntimeException(e); } }
From source file:com.ikon.util.MailUtils.java
/** * Create a mail from a Mail object/*from w w w. ja v a2s . c o m*/ */ public static MimeMessage create(String token, Mail mail) throws MessagingException, PathNotFoundException, AccessDeniedException, RepositoryException, IOException, DatabaseException { log.debug("create({})", mail); Session mailSession = getMailSession(); MimeMessage msg = new MimeMessage(mailSession); if (mail.getFrom() != null) { InternetAddress from = new InternetAddress(mail.getFrom()); msg.setFrom(from); } else { msg.setFrom(); } InternetAddress[] to = new InternetAddress[mail.getTo().length]; int i = 0; for (String strTo : mail.getTo()) { to[i++] = new InternetAddress(strTo); } // Build a multiparted mail with HTML and text content for better SPAM behaviour MimeMultipart content = new MimeMultipart(); if (Mail.MIME_TEXT.equals(mail.getMimeType())) { // Text part MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(mail.getContent()); textPart.setHeader("Content-Type", "text/plain"); textPart.setDisposition(Part.INLINE); content.addBodyPart(textPart); } else if (Mail.MIME_HTML.equals(mail.getMimeType())) { // HTML Part MimeBodyPart htmlPart = new MimeBodyPart(); StringBuilder htmlContent = new StringBuilder(); htmlContent.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n"); htmlContent.append("<html>\n<head>\n"); htmlContent.append("<meta content=\"text/html;charset=UTF-8\" http-equiv=\"Content-Type\"/>\n"); htmlContent.append("</head>\n<body>\n"); htmlContent.append(mail.getContent()); htmlContent.append("\n</body>\n</html>"); htmlPart.setContent(htmlContent.toString(), "text/html"); htmlPart.setHeader("Content-Type", "text/html"); htmlPart.setDisposition(Part.INLINE); content.addBodyPart(htmlPart); } else { log.warn("Email does not specify content MIME type"); // Text part MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(mail.getContent()); textPart.setHeader("Content-Type", "text/plain"); textPart.setDisposition(Part.INLINE); content.addBodyPart(textPart); } for (Document doc : mail.getAttachments()) { InputStream is = null; FileOutputStream fos = null; String docName = PathUtils.getName(doc.getPath()); try { is = OKMDocument.getInstance().getContent(token, doc.getPath(), false); File tmp = File.createTempFile("okm", ".tmp"); fos = new FileOutputStream(tmp); IOUtils.copy(is, fos); fos.flush(); // Document attachment part MimeBodyPart docPart = new MimeBodyPart(); DataSource source = new FileDataSource(tmp.getPath()); docPart.setDataHandler(new DataHandler(source)); docPart.setFileName(docName); docPart.setDisposition(Part.ATTACHMENT); content.addBodyPart(docPart); } finally { IOUtils.closeQuietly(is); IOUtils.closeQuietly(fos); } } msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", content.getContentType()); msg.addHeader("Charset", "UTF-8"); msg.setRecipients(Message.RecipientType.TO, to); msg.setSubject(mail.getSubject(), "UTF-8"); msg.setSentDate(new Date()); msg.setContent(content); msg.saveChanges(); log.debug("create: {}", msg); return msg; }
From source file:com.mylab.mail.OpenCmsMailService.java
public void sendMultipartMail(MessageConfig config, DataSource imageds, String image, DataSource audiods, String audio) throws MessagingException { log.debug("Sending multipart message " + config); Session session = getSession();/*from ww w. j av a 2 s . co m*/ MimeMultipart multipart = new MimeMultipart(); MimeBodyPart html = new MimeBodyPart(); html.setContent(config.getContent(), config.getContentType()); html.setHeader("MIME-Version", "1.0"); html.setHeader("Content-Type", html.getContentType()); multipart.addBodyPart(html); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(imageds)); messageBodyPart.setFileName(image); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(audiods)); messageBodyPart.setFileName(audio); multipart.addBodyPart(messageBodyPart); final MimeMessage message = new MimeMessage(session); message.setContent(multipart); try { message.setFrom(new InternetAddress(config.getFrom(), config.getFromName())); addRecipientsWhitelist(message, config.getTo(), config.getToName(), config.getCardconfig()); } catch (UnsupportedEncodingException ex) { throw new MessagingException("Setting from or to failed", ex); } message.setSubject(config.getSubject()); // we don't send in a new Thread so that we get the Exception Transport.send(message); }
From source file:com.haulmont.cuba.core.app.EmailSender.java
protected MimeBodyPart createAttachmentPart(SendingAttachment attachment) throws MessagingException { DataSource source = new MyByteArrayDataSource(attachment.getContent()); String mimeType = FileTypesHelper.getMIMEType(attachment.getName()); String encodedFileName = encodeAttachmentName(attachment); String contentId = attachment.getContentId(); if (contentId == null) { contentId = encodedFileName;//from www . j a v a 2 s . co m } String disposition = attachment.getDisposition() != null ? attachment.getDisposition() : Part.INLINE; String charset = MimeUtility.mimeCharset( attachment.getEncoding() != null ? attachment.getEncoding() : StandardCharsets.UTF_8.name()); String contentTypeValue = String.format("%s; charset=%s; name=\"%s\"", mimeType, charset, encodedFileName); MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setDataHandler(new DataHandler(source)); attachmentPart.setHeader("Content-ID", "<" + contentId + ">"); attachmentPart.setHeader("Content-Type", contentTypeValue); attachmentPart.setFileName(encodedFileName); attachmentPart.setDisposition(disposition); return attachmentPart; }
From source file:com.adaptris.core.MimeEncoderImpl.java
protected MimeBodyPart payloadAsMimePart(AdaptrisMessage m) throws Exception { MimeBodyPart p = new MimeBodyPart(); p.setDataHandler(new DataHandler(new MessageDataSource(m))); if (!isEmpty(getPayloadEncoding())) { p.setHeader(MimeConstants.HEADER_CONTENT_ENCODING, getPayloadEncoding()); }//from www. j a v a 2s . co m return p; }
From source file:com.meltmedia.cadmium.email.TestingMessageTransformer.java
public MimeBodyPart newSentToBodyPart(MimeMessage message) throws MessagingException { // get information about the original message. Address[] originalFromRecipient = message.getFrom(); Address[] originalToRecipient = message.getRecipients(Message.RecipientType.TO); Address[] originalCcRecipient = message.getRecipients(Message.RecipientType.CC); Address[] originalBccRecipient = message.getRecipients(Message.RecipientType.BCC); String originalSubject = message.getSubject(); // create the html for the string buffer. StringBuffer html = new StringBuffer(); html.append("<html><body><table style=\"width: 100%;\"><tr><td>header</td><td>value</td></tr>"); html.append("<tr><td>Subject:</td><td>").append(escape(originalSubject)).append("</td></tr>"); // iterate over the addresses. if (originalFromRecipient != null) { for (int i = 0; i < originalFromRecipient.length; i++) { html.append("<tr><td>FROM:</td><td>").append(escape(originalFromRecipient[i])).append("</td></tr>"); }//from w w w .ja v a2 s . c om } if (originalToRecipient != null) { for (int i = 0; i < originalToRecipient.length; i++) { html.append("<tr><td>TO:</td><td>").append(escape(originalToRecipient[i])).append("</td></tr>"); } } if (originalCcRecipient != null) { for (int i = 0; i < originalCcRecipient.length; i++) { html.append("<tr><td>CC:</td><td>").append(escape(originalCcRecipient[i])).append("</td></tr>"); } } if (originalBccRecipient != null) { for (int i = 0; i < originalBccRecipient.length; i++) { html.append("<tr><td>BCC:</td><td>").append(escape(originalBccRecipient[i])).append("</td></tr>"); } } html.append("</table></body></html>"); MimeBodyPart sentToBodyPart = new MimeBodyPart(); sentToBodyPart.setContent(html.toString(), "text/html"); sentToBodyPart.setHeader("Content-ID", "original-addresses"); sentToBodyPart.setDisposition("inline"); return sentToBodyPart; }
From source file:com.linkedin.r2.message.rest.QueryTunnelUtil.java
/** * Helper function to create multi-part MIME * * @param entity the body of a request * @param entityContentType content type of the body * @param query a query part of a request * * @return a ByteString that represents a multi-part encoded entity that contains both *//*from w w w. j ava2s.co m*/ private static MimeMultipart createMultiPartEntity(final ByteString entity, final String entityContentType, String query) throws MessagingException { MimeMultipart multi = new MimeMultipart(MIXED); // Create current entity with the associated type MimeBodyPart dataPart = new MimeBodyPart(); ContentType contentType = new ContentType(entityContentType); if (MULTIPART.equals(contentType.getBaseType())) { MimeMultipart nested = new MimeMultipart(new DataSource() { @Override public InputStream getInputStream() throws IOException { return entity.asInputStream(); } @Override public OutputStream getOutputStream() throws IOException { return null; } @Override public String getContentType() { return entityContentType; } @Override public String getName() { return null; } }); dataPart.setContent(nested, contentType.getBaseType()); } else { dataPart.setContent(entity.copyBytes(), contentType.getBaseType()); } dataPart.setHeader(HEADER_CONTENT_TYPE, entityContentType); // Encode query params as form-urlencoded MimeBodyPart argPart = new MimeBodyPart(); argPart.setContent(query, FORM_URL_ENCODED); argPart.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED); multi.addBodyPart(argPart); multi.addBodyPart(dataPart); return multi; }
From source file:it.ozimov.springboot.templating.mail.service.EmailServiceImpl.java
public MimeMessage send(final @NonNull Email email, final @NonNull String template, final Map<String, Object> modelObject, final @NonNull InlinePicture... inlinePictures) throws CannotSendEmailException { email.setSentAt(new Date()); final MimeMessage mimeMessage = toMimeMessage(email); try {//from ww w.j a va 2s. com final MimeMultipart content = new MimeMultipart("related"); String text = templateService.mergeTemplateIntoString(template, fromNullable(modelObject).or(ImmutableMap.of())); for (final InlinePicture inlinePicture : inlinePictures) { final String cid = UUID.randomUUID().toString(); //Set the cid in the template text = text.replace(inlinePicture.getTemplateName(), "cid:" + cid); //Set the image part final MimeBodyPart imagePart = new MimeBodyPart(); imagePart.attachFile(inlinePicture.getFile()); imagePart.setContentID('<' + cid + '>'); imagePart.setDisposition(MimeBodyPart.INLINE); imagePart.setHeader("Content-Type", inlinePicture.getImageType().getContentType()); content.addBodyPart(imagePart); } //Set the HTML text part final MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(text, email.getEncoding().displayName(), "html"); content.addBodyPart(textPart); mimeMessage.setContent(content); javaMailSender.send(mimeMessage); } catch (IOException e) { log.error("The template file cannot be read", e); throw new CannotSendEmailException( "Error while sending the email due to problems with the template file", e); } catch (TemplateException e) { log.error("The template file cannot be processed", e); throw new CannotSendEmailException( "Error while processing the template file with the given model object", e); } catch (MessagingException e) { log.error("The mime message cannot be created", e); throw new CannotSendEmailException( "Error while sending the email due to problems with the mime content", e); } return mimeMessage; }
From source file:org.nuxeo.ecm.automation.client.jaxrs.impl.MultipartRequestEntity.java
protected void setBlob(Blob blob, String id) throws MessagingException, IOException { MimeBodyPart part = new MimeBodyPart(); if (blob instanceof HasFile) { part.attachFile(((HasFile) blob).getFile()); } else {/*from www .j av a 2 s .c o m*/ part.setDataHandler(new DataHandler(new BlobDataSource(blob))); part.setFileName(blob.getFileName()); } part.setHeader("Content-Type", blob.getMimeType()); part.setHeader("Content-Transfer-Encoding", "binary"); int length = blob.getLength(); if (length > -1) { part.setHeader("Content-Length", Integer.toString(length)); } part.setContentID(id); mp.addBodyPart(part); }
From source file:com.adaptris.mail.MailSenderImp.java
private void addEmailBody(MimeMultipart multipart) throws MailException { try {//ww w .j av a 2s .c o m if (emailBody != null) { MimeBodyPart part = create(emailBody, new InternetHeaders(), encoding); part.setHeader(Mail.CONTENT_TYPE, bodyContentType); multipart.addBodyPart(part); } } catch (Exception e) { throw new MailException(e); } }