List of usage examples for javax.mail.internet MimeMessage setContent
@Override public void setContent(Multipart mp) throws MessagingException
From source file:org.apache.james.transport.mailets.managesieve.ManageSieveMailetTestCase.java
private MimeMessage prepareMessageWithAttachment(String scriptContent, String subject) throws MessagingException, IOException { MimeMessage message = prepareMimeMessage(subject); MimeMultipart multipart = new MimeMultipart(); MimeBodyPart scriptPart = new MimeBodyPart(); scriptPart.setDataHandler(/*from w w w . ja va 2s . c om*/ new DataHandler(new ByteArrayDataSource(scriptContent, "application/sieve; charset=UTF-8"))); scriptPart.setDisposition(MimeBodyPart.ATTACHMENT); // setting a DataHandler with no mailcap definition is not // supported by the specs. Javamail activation still work, // but Geronimo activation translate it to text/plain. // Let's manually force the header. scriptPart.setHeader("Content-Type", "application/sieve; charset=UTF-8"); scriptPart.setFileName(SCRIPT_NAME); multipart.addBodyPart(scriptPart); message.setContent(multipart); message.saveChanges(); return message; }
From source file:com.tdclighthouse.commons.mail.util.MailClient.java
public void sendMail(String from, String[] to, Mail mail) throws MessagingException, AddressException { // a brief validation if ((from == null) || "".equals(from) || (to.length == 0) || (mail == null)) { throw new IllegalArgumentException(); }/* w w w.ja v a2 s. c om*/ Session session = getSession(); // Define a new mail message MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); for (int i = 0; i < to.length; i++) { message.addRecipient(Message.RecipientType.TO, new InternetAddress(to[i])); } message.setSubject(mail.getSubject(), "utf-8"); // use a MimeMultipart as we need to handle the file attachments Multipart multipart = new MimeMultipart("alternative"); if ((mail.getMessageBody() != null) && !"".equals(mail.getMessageBody())) { // add the message body to the mime message BodyPart textPart = new MimeBodyPart(); textPart.setContent(mail.getMessageBody(), "text/plain; charset=utf-8"); // sets type to "text/plain" multipart.addBodyPart(textPart); } if (mail.getHtmlBody() != null) { BodyPart pixPart = new MimeBodyPart(); pixPart.setContent(mail.getHtmlBody(), "text/html; charset=utf-8"); multipart.addBodyPart(pixPart); } // add any file attachments to the message addAtachments(mail.getAttachments(), multipart); // Put all message parts in the message message.setContent(multipart); // Send the message Transport.send(message); }
From source file:org.apache.james.transport.mailets.StripAttachmentTest.java
@Test public void testSimpleAttachment3() throws MessagingException, IOException { Mailet mailet = initMailet();/* w ww . j ava 2 s .c o m*/ // System.setProperty("mail.mime.decodefilename", "true"); MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties())); MimeMultipart mm = new MimeMultipart(); MimeBodyPart mp = new MimeBodyPart(); mp.setText("simple text"); mm.addBodyPart(mp); String body = "\u0023\u00A4\u00E3\u00E0\u00E9"; MimeBodyPart mp2 = new MimeBodyPart( new ByteArrayInputStream(("Content-Transfer-Encoding: 8bit\r\n\r\n" + body).getBytes("UTF-8"))); mp2.setDisposition("attachment"); mp2.setFileName("=?iso-8859-15?Q?=E9_++++Pubblicit=E0_=E9_vietata____Milano9052.tmp?="); mm.addBodyPart(mp2); String body2 = "\u0014\u00A3\u00E1\u00E2\u00E4"; MimeBodyPart mp3 = new MimeBodyPart( new ByteArrayInputStream(("Content-Transfer-Encoding: 8bit\r\n\r\n" + body2).getBytes("UTF-8"))); mp3.setDisposition("attachment"); mp3.setFileName("temp.zip"); mm.addBodyPart(mp3); message.setSubject("test"); message.setContent(mm); message.saveChanges(); // message.writeTo(System.out); // System.out.println("--------------------------\n\n\n"); Mail mail = FakeMail.builder().mimeMessage(message).build(); mailet.service(mail); ByteArrayOutputStream rawMessage = new ByteArrayOutputStream(); mail.getMessage().writeTo(rawMessage, new String[] { "Bcc", "Content-Length", "Message-ID" }); // String res = rawMessage.toString(); @SuppressWarnings("unchecked") Collection<String> c = (Collection<String>) mail .getAttribute(StripAttachment.SAVED_ATTACHMENTS_ATTRIBUTE_KEY); Assert.assertNotNull(c); Assert.assertEquals(1, c.size()); String name = c.iterator().next(); // System.out.println("--------------------------\n\n\n"); // System.out.println(name); Assert.assertTrue(name.startsWith("e_Pubblicita_e_vietata_Milano9052")); File f = new File("./" + name); try { InputStream is = new FileInputStream(f); String savedFile = toString(is); is.close(); Assert.assertEquals(body, savedFile); } finally { FileUtils.deleteQuietly(f); } }
From source file:com.threewks.thundr.gmail.GmailMailer.java
private MimeMessage createMime(String bodyText, String subject, Map<String, String> to, List<Attachment> pdfs) throws MessagingException { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); Set<InternetAddress> toAddresses = getInternetAddresses(to); if (!toAddresses.isEmpty()) { email.addRecipients(javax.mail.Message.RecipientType.TO, toAddresses.toArray(new InternetAddress[to.size()])); }/* w w w . j a va 2 s . c o m*/ email.setSubject(subject); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(bodyText, "text/html"); mimeBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\""); Multipart multipart = new MimeMultipart(); for (Attachment attachmentPdf : pdfs) { MimeBodyPart attachment = new MimeBodyPart(); DataSource source = new ByteArrayDataSource(attachmentPdf.getData(), "application/pdf"); attachment.setDataHandler(new DataHandler(source)); attachment.setFileName(attachmentPdf.getFileName()); multipart.addBodyPart(mimeBodyPart); multipart.addBodyPart(attachment); } email.setContent(multipart); return email; }
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 w w w. j a va 2 s. c om 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.eclipse.che.mail.MailSender.java
public void sendMail(EmailBean emailBean) throws SendMailException { File tempDir = null;//www .j a v a 2 s . com try { MimeMessage message = new MimeMessage(mailSessionProvider.get()); Multipart contentPart = new MimeMultipart(); MimeBodyPart bodyPart = new MimeBodyPart(); bodyPart.setText(emailBean.getBody(), "UTF-8", getSubType(emailBean.getMimeType())); contentPart.addBodyPart(bodyPart); if (emailBean.getAttachments() != null) { tempDir = Files.createTempDir(); for (Attachment attachment : emailBean.getAttachments()) { // Create attachment file in temporary directory byte[] attachmentContent = Base64.getDecoder().decode(attachment.getContent()); File attachmentFile = new File(tempDir, attachment.getFileName()); Files.write(attachmentContent, attachmentFile); // Attach the attachment file to email MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.attachFile(attachmentFile); attachmentPart.setContentID("<" + attachment.getContentId() + ">"); contentPart.addBodyPart(attachmentPart); } } message.setContent(contentPart); message.setSubject(emailBean.getSubject(), "UTF-8"); message.setFrom(new InternetAddress(emailBean.getFrom(), true)); message.setSentDate(new Date()); message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(emailBean.getTo())); if (emailBean.getReplyTo() != null) { message.setReplyTo(InternetAddress.parse(emailBean.getReplyTo())); } LOG.info("Sending from {} to {} with subject {}", emailBean.getFrom(), emailBean.getTo(), emailBean.getSubject()); Transport.send(message); LOG.debug("Mail sent"); } catch (Exception e) { LOG.error(e.getLocalizedMessage()); throw new SendMailException(e.getLocalizedMessage(), e); } finally { if (tempDir != null) { try { FileUtils.deleteDirectory(tempDir); } catch (IOException exception) { LOG.error(exception.getMessage()); } } } }
From source file:com.meltmedia.cadmium.email.TestingMessageTransformer.java
public MimeMessage transform(MimeMessage message) throws MessagingException { MimeBodyPart sentToBodyPart = newSentToBodyPart(message); MimeBodyPart originalBodyPart = newOriginalBodyPart(message); // create a new multipart content for this message. MimeMultipart multipart = new MimeMultipart(EmailUtil.SUBTYPE_MIXED); // add the parts to the body. multipart.addBodyPart(originalBodyPart); multipart.addBodyPart(sentToBodyPart); // get the new values for all of the headers. InternetAddress newFromAddress = newFromAddress(message); InternetAddress[] newToAddresses = newToAddresses(message); InternetAddress[] newCcAddresses = newCcAddresses(message); InternetAddress[] newBccAddresses = newBccAddresses(message); String newSubject = newSubject(message); // update the message. message.setFrom(newFromAddress);//ww w . j ava2s. co m message.setRecipients(Message.RecipientType.TO, newToAddresses); message.setRecipients(Message.RecipientType.CC, newCcAddresses); message.setRecipients(Message.RecipientType.BCC, newBccAddresses); message.setSubject(newSubject); message.setContent(multipart); // save the message. message.saveChanges(); if (getLogProperty()) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); message.writeTo(out); log.info("Email Message Sent:\n{}", out.toString()); } catch (IOException ioe) { throw new MessagingException("Exception thrown while writing message to log.", ioe); } } if (!getSendProperty()) { message = null; } // return the message. return message; }
From source file:rescustomerservices.GmailQuickstart.java
/** * Create a MimeMessage using the parameters provided. * * @param to Email address of the receiver. * @param from Email address of the sender, the mailbox account. * @param subject Subject of the email./*ww w. ja v a2s.c o m*/ * @param bodyText Body text of the email. * @param fileDir Path to the directory containing attachment. * @param filename Name of file to be attached. * @return MimeMessage to be used to send email. * @throws MessagingException */ public MimeMessage createEmailWithAttachment(String to, String from, String subject, String bodyText, String fileDir, String filename) throws MessagingException, IOException { Properties props = new Properties(); Session session = Session.getDefaultInstance(props, null); MimeMessage email = new MimeMessage(session); InternetAddress tAddress = new InternetAddress(to); InternetAddress fAddress = new InternetAddress(from); email.setFrom(fAddress); email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress); email.setSubject(subject); MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(bodyText, "text/plain"); mimeBodyPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\""); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(mimeBodyPart); mimeBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(fileDir + filename); mimeBodyPart.setDataHandler(new DataHandler(source)); mimeBodyPart.setFileName(filename); String contentType = Files.probeContentType(FileSystems.getDefault().getPath(fileDir, filename)); mimeBodyPart.setHeader("Content-Type", contentType + "; name=\"" + filename + "\""); mimeBodyPart.setHeader("Content-Transfer-Encoding", "base64"); multipart.addBodyPart(mimeBodyPart); email.setContent(multipart); return email; }
From source file:com.trivago.mail.pigeon.mail.MailFacade.java
public void sendMail(MailTransport mailTransport) { log.debug("Mail delivery started"); File propertyfile = ((PropertiesConfiguration) Settings.create().getConfiguration()).getFile(); Properties config = new Properties(); try {/*from www .j a v a 2 s . c o m*/ config.load(new FileReader(propertyfile)); } catch (IOException e) { log.error(e); } Session session = Session.getDefaultInstance(config); log.debug("Received session"); MimeMessage message = new MimeMessage(session); String to = mailTransport.getTo(); String from = mailTransport.getFrom(); String replyTo = mailTransport.getReplyTo(); String subject = mailTransport.getSubject(); String html = mailTransport.getHtml(); String text = mailTransport.getText(); try { Address fromAdr = new InternetAddress(from); Address toAdr = new InternetAddress(to); Address rplyAdr = new InternetAddress(replyTo); message.setSubject(subject); message.setFrom(fromAdr); message.setRecipient(Message.RecipientType.TO, toAdr); message.setReplyTo(new Address[] { rplyAdr }); message.setSender(fromAdr); message.addHeader("Return-path", replyTo); message.addHeader("X-TRV-MID", mailTransport.getmId()); message.addHeader("X-TRV-UID", mailTransport.getuId()); // Content MimeBodyPart messageTextPart = new MimeBodyPart(); messageTextPart.setText(text); messageTextPart.setContent(html, "text/html"); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageTextPart); // Put parts in message message.setContent(multipart); log.debug("Dispatching message"); Transport.send(message); log.debug("Mail delivery ended"); } catch (MessagingException e) { log.error(e); } }
From source file:org.apache.james.transport.mailets.StripAttachmentTest.java
@Test public void testSimpleAttachment() throws MessagingException, IOException { Mailet mailet = initMailet();/* w ww .ja v a2s. co m*/ MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties())); MimeMultipart mm = new MimeMultipart(); MimeBodyPart mp = new MimeBodyPart(); mp.setText("simple text"); mm.addBodyPart(mp); String body = "\u0023\u00A4\u00E3\u00E0\u00E9"; MimeBodyPart mp2 = new MimeBodyPart(new ByteArrayInputStream( ("Content-Transfer-Encoding: 8bit\r\nContent-Type: application/octet-stream; charset=utf-8\r\n\r\n" + body).getBytes("UTF-8"))); mp2.setDisposition("attachment"); mp2.setFileName("10.tmp"); mm.addBodyPart(mp2); String body2 = "\u0014\u00A3\u00E1\u00E2\u00E4"; MimeBodyPart mp3 = new MimeBodyPart(new ByteArrayInputStream( ("Content-Transfer-Encoding: 8bit\r\nContent-Type: application/octet-stream; charset=utf-8\r\n\r\n" + body2).getBytes("UTF-8"))); mp3.setDisposition("attachment"); mp3.setFileName("temp.zip"); mm.addBodyPart(mp3); message.setSubject("test"); message.setContent(mm); message.saveChanges(); Mail mail = FakeMail.builder().mimeMessage(message).build(); mailet.service(mail); ByteArrayOutputStream rawMessage = new ByteArrayOutputStream(); mail.getMessage().writeTo(rawMessage, new String[] { "Bcc", "Content-Length", "Message-ID" }); @SuppressWarnings("unchecked") Collection<String> c = (Collection<String>) mail .getAttribute(StripAttachment.SAVED_ATTACHMENTS_ATTRIBUTE_KEY); Assert.assertNotNull(c); Assert.assertEquals(1, c.size()); String name = c.iterator().next(); File f = new File("./" + name); try { InputStream is = new FileInputStream(f); String savedFile = toString(is); is.close(); Assert.assertEquals(body, savedFile); } finally { FileUtils.deleteQuietly(f); } }