List of usage examples for javax.mail BodyPart setContent
public void setContent(Object obj, String type) throws MessagingException;
From source file:lucee.runtime.net.mail.HtmlEmailImpl.java
/** * @throws EmailException EmailException * @throws MessagingException MessagingException *///w w w. j a v a2 s .c o m private void buildNoAttachments() throws MessagingException, EmailException { MimeMultipart container = this.getContainer(); MimeMultipart subContainerHTML = new MimeMultipart("related"); container.setSubType("alternative"); BodyPart msgText = null; BodyPart msgHtml = null; if (!StringUtil.isEmpty(this.text)) { msgText = this.getPrimaryBodyPart(); if (!StringUtil.isEmpty(this.charset)) { msgText.setContent(this.text, Email.TEXT_PLAIN + "; charset=" + this.charset); } else { msgText.setContent(this.text, Email.TEXT_PLAIN); } } if (!StringUtil.isEmpty(this.html)) { // if the txt part of the message was null, then the html part // will become the primary body part if (msgText == null) { msgHtml = getPrimaryBodyPart(); } else { if (this.inlineImages.size() > 0) { msgHtml = new MimeBodyPart(); subContainerHTML.addBodyPart(msgHtml); } else { msgHtml = new MimeBodyPart(); container.addBodyPart(msgHtml, 1); } } if (!StringUtil.isEmpty(this.charset)) { msgHtml.setContent(this.html, Email.TEXT_HTML + "; charset=" + this.charset); } else { msgHtml.setContent(this.html, Email.TEXT_HTML); } Iterator iter = this.inlineImages.iterator(); while (iter.hasNext()) { subContainerHTML.addBodyPart((BodyPart) iter.next()); } if (this.inlineImages.size() > 0) { // add sub container to message this.addPart(subContainerHTML); } } }
From source file:fr.xebia.demo.amazon.aws.AmazonAwsIamAccountCreatorV2.java
/** * Send email with Amazon Simple Email Service. * <p/>/*from w ww . ja v a 2s . c om*/ * * Please note that the sender (ie 'from') must be a verified address (see * {@link AmazonSimpleEmailService#verifyEmailAddress(com.amazonaws.services.simpleemail.model.VerifyEmailAddressRequest)} * ). * <p/> * * Please note that the sender is a CC of the meail to ease support. * <p/> * * @param subject * @param body * @param from * @param toAddresses * @throws MessagingException * @throws AddressException */ public void sendEmail(String subject, String body, AccessKey accessKey, KeyPair sshKeyPair, java.security.KeyPair x509KeyPair, X509Certificate x509Certificate, SigningCertificate signingCertificate, String from, String toAddress) { try { Session s = Session.getInstance(new Properties(), null); MimeMessage msg = new MimeMessage(s); msg.setFrom(new InternetAddress(from)); msg.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toAddress)); msg.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(from)); msg.setSubject(subject); MimeMultipart mimeMultiPart = new MimeMultipart(); msg.setContent(mimeMultiPart); // body BodyPart plainTextBodyPart = new MimeBodyPart(); mimeMultiPart.addBodyPart(plainTextBodyPart); plainTextBodyPart.setContent(body, "text/plain"); // aws-credentials.txt / accessKey { BodyPart awsCredentialsBodyPart = new MimeBodyPart(); awsCredentialsBodyPart.setFileName("aws-credentials.txt"); StringWriter awsCredentialsStringWriter = new StringWriter(); PrintWriter awsCredentials = new PrintWriter(awsCredentialsStringWriter); awsCredentials .println("#Insert your AWS Credentials from http://aws.amazon.com/security-credentials"); awsCredentials.println("#" + new DateTime()); awsCredentials.println(); awsCredentials.println("# ec2, rds & elb tools use accessKey and secretKey"); awsCredentials.println("accessKey=" + accessKey.getAccessKeyId()); awsCredentials.println("secretKey=" + accessKey.getSecretAccessKey()); awsCredentials.println(); awsCredentials.println("# iam tools use AWSAccessKeyId and AWSSecretKey"); awsCredentials.println("AWSAccessKeyId=" + accessKey.getAccessKeyId()); awsCredentials.println("AWSSecretKey=" + accessKey.getSecretAccessKey()); awsCredentialsBodyPart.setContent(awsCredentialsStringWriter.toString(), "text/plain"); mimeMultiPart.addBodyPart(awsCredentialsBodyPart); } // private ssh key { BodyPart keyPairBodyPart = new MimeBodyPart(); keyPairBodyPart.setFileName(sshKeyPair.getKeyName() + ".pem.txt"); keyPairBodyPart.setContent(sshKeyPair.getKeyMaterial(), "application/octet-stream"); mimeMultiPart.addBodyPart(keyPairBodyPart); } // x509 private key { BodyPart x509PrivateKeyBodyPart = new MimeBodyPart(); x509PrivateKeyBodyPart.setFileName("pk-" + signingCertificate.getCertificateId() + ".pem.txt"); String x509privateKeyPem = Pems.pem(x509KeyPair.getPrivate()); x509PrivateKeyBodyPart.setContent(x509privateKeyPem, "application/octet-stream"); mimeMultiPart.addBodyPart(x509PrivateKeyBodyPart); } // x509 private key { BodyPart x509CertificateBodyPart = new MimeBodyPart(); x509CertificateBodyPart.setFileName("cert-" + signingCertificate.getCertificateId() + ".pem.txt"); String x509CertificatePem = Pems.pem(x509Certificate); x509CertificateBodyPart.setContent(x509CertificatePem, "application/octet-stream"); mimeMultiPart.addBodyPart(x509CertificateBodyPart); } // Convert to raw message ByteArrayOutputStream out = new ByteArrayOutputStream(); msg.writeTo(out); RawMessage rawMessage = new RawMessage(); rawMessage.setData(ByteBuffer.wrap(out.toString().getBytes())); ses.sendRawEmail(new SendRawEmailRequest().withRawMessage(rawMessage)); } catch (Exception e) { throw Throwables.propagate(e); } }
From source file:com.netflix.ice.basic.BasicWeeklyCostEmailService.java
private void sendEmail(boolean test, AmazonSimpleEmailServiceClient emailService, String email, List<ApplicationGroup> appGroups) throws IOException, MessagingException { StringBuilder body = new StringBuilder(); body.append(//from w w w . j a v a 2 s . c o m "<html><head><style type=\"text/css\">a:link, a:visited{color:#006DBA;}a:link, a:visited, a:hover {\n" + "text-decoration: none;\n" + "}\n" + "body {\n" + "color: #333;\n" + "}" + "</style></head>"); List<MimeBodyPart> mimeBodyParts = Lists.newArrayList(); int index = 0; String subject = ""; for (ApplicationGroup appGroup : appGroups) { boolean hasData = false; for (String prodName : appGroup.data.keySet()) { if (config.productService.getProductByName(prodName) == null) continue; hasData = appGroup.data.get(prodName) != null && appGroup.data.get(prodName).size() > 0; if (hasData) break; } if (!hasData) continue; try { MimeBodyPart mimeBodyPart = constructEmail(index, appGroup, body); index++; if (mimeBodyPart != null) { mimeBodyParts.add(mimeBodyPart); subject = subject + (subject.length() > 0 ? ", " : "") + appGroup.getDisplayName(); } } catch (Exception e) { logger.error("Error contructing email", e); } } body.append("</html>"); if (mimeBodyParts.size() == 0) return; DateTime end = new DateTime(DateTimeZone.UTC).withDayOfWeek(1).withMillisOfDay(0); subject = String.format("%s Weekly AWS Costs (%s - %s)", subject, formatter.print(end.minusWeeks(1)), formatter.print(end)); String toEmail = test ? testEmail : email; Session session = Session.getInstance(new Properties()); MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setSubject(subject); mimeMessage.setRecipients(javax.mail.Message.RecipientType.TO, toEmail); if (!test && !StringUtils.isEmpty(bccEmail)) { mimeMessage.addRecipients(Message.RecipientType.BCC, bccEmail); } MimeMultipart mimeMultipart = new MimeMultipart(); BodyPart p = new MimeBodyPart(); p.setContent(body.toString(), "text/html"); mimeMultipart.addBodyPart(p); for (MimeBodyPart mimeBodyPart : mimeBodyParts) mimeMultipart.addBodyPart(mimeBodyPart); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); mimeMessage.setContent(mimeMultipart); mimeMessage.writeTo(outputStream); RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray())); SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage); rawEmailRequest.setDestinations(Lists.<String>newArrayList(toEmail)); rawEmailRequest.setSource(fromEmail); logger.info("sending email to " + toEmail + " " + body.toString()); emailService.sendRawEmail(rawEmailRequest); }
From source file:lucee.runtime.net.mail.HtmlEmailImpl.java
/** * @throws EmailException EmailException * @throws MessagingException MessagingException *///from w w w . j a va 2 s . c o m private void buildAttachments() throws MessagingException, EmailException { MimeMultipart container = this.getContainer(); MimeMultipart subContainer = null; MimeMultipart subContainerHTML = new MimeMultipart("related"); BodyPart msgHtml = null; BodyPart msgText = null; container.setSubType("mixed"); subContainer = new MimeMultipart("alternative"); if (!StringUtil.isEmpty(this.text)) { msgText = new MimeBodyPart(); subContainer.addBodyPart(msgText); if (!StringUtil.isEmpty(this.charset)) { msgText.setContent(this.text, Email.TEXT_PLAIN + "; charset=" + this.charset); } else { msgText.setContent(this.text, Email.TEXT_PLAIN); } } if (!StringUtil.isEmpty(this.html)) { if (this.inlineImages.size() > 0) { msgHtml = new MimeBodyPart(); subContainerHTML.addBodyPart(msgHtml); } else { msgHtml = new MimeBodyPart(); subContainer.addBodyPart(msgHtml); } if (!StringUtil.isEmpty(this.charset)) { msgHtml.setContent(this.html, Email.TEXT_HTML + "; charset=" + this.charset); } else { msgHtml.setContent(this.html, Email.TEXT_HTML); } Iterator iter = this.inlineImages.iterator(); while (iter.hasNext()) { subContainerHTML.addBodyPart((BodyPart) iter.next()); } } // add sub containers to message this.addPart(subContainer, 0); if (this.inlineImages.size() > 0) { // add sub container to message this.addPart(subContainerHTML, 1); } }
From source file:nc.noumea.mairie.appock.services.impl.MailServiceImpl.java
private void gereBonLivraisonDansMail(AppockMail appockMail, MimeMessage msg, String contenuFinal) throws MessagingException { if (appockMail.getBonLivraison() == null) { msg.setContent(contenuFinal, "text/html; charset=utf-8"); } else {/*w w w.j a v a 2s.c om*/ BonLivraison bonLivraison = appockMail.getBonLivraison(); Multipart multipart = new MimeMultipart(); BodyPart attachmentBodyPart = new MimeBodyPart(); File file = commandeServiceService.getFileBonLivraison(appockMail.getBonLivraison()); ByteArrayDataSource bds = null; try { bds = new ByteArrayDataSource(Files.readAllBytes(file.toPath()), bonLivraison.getMimeType().getLibelle()); } catch (IOException e) { e.printStackTrace(); } attachmentBodyPart.setDataHandler(new DataHandler(bds)); attachmentBodyPart.setFileName(bonLivraison.getNomFichier()); multipart.addBodyPart(attachmentBodyPart); BodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(contenuFinal, "text/html; charset=utf-8"); multipart.addBodyPart(htmlBodyPart); msg.setContent(multipart); } }
From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java
private void sendEmail(Map<String, String> templatesParams, List<BodyPart> attachments, String toAddress) throws MessagingException { MimeBodyPart htmlAndPlainTextAlternativeBody = new MimeBodyPart(); // TEXT AND HTML MESSAGE (gmail requires plain text alternative, otherwise, it displays the 1st plain text attachment in the preview) MimeMultipart cover = new MimeMultipart("alternative"); htmlAndPlainTextAlternativeBody.setContent(cover); BodyPart textHtmlBodyPart = new MimeBodyPart(); String textHtmlBody = FreemarkerUtils.generate(templatesParams, "/fr/xebia/cloud/amazon/aws/iam/amazon-aws-iam-credentials-email-" + environment.getIdentifier() + ".html.ftl"); textHtmlBodyPart.setContent(textHtmlBody, "text/html"); cover.addBodyPart(textHtmlBodyPart); BodyPart textPlainBodyPart = new MimeBodyPart(); cover.addBodyPart(textPlainBodyPart); String textPlainBody = FreemarkerUtils.generate(templatesParams, "/fr/xebia/cloud/amazon/aws/iam/amazon-aws-iam-credentials-email-" + environment.getIdentifier() + ".txt.ftl"); textPlainBodyPart.setContent(textPlainBody, "text/plain"); MimeMultipart content = new MimeMultipart("related"); content.addBodyPart(htmlAndPlainTextAlternativeBody); // ATTACHMENTS for (BodyPart bodyPart : attachments) { content.addBodyPart(bodyPart);//from ww w . j a v a 2s . co m } MimeMessage msg = new MimeMessage(mailSession); msg.setFrom(mailFrom); msg.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toAddress)); msg.addRecipient(javax.mail.Message.RecipientType.CC, mailFrom); String subject = "[Xebia Amazon AWS " + environment.getIdentifier() + "] Credentials"; msg.setSubject(subject); msg.setContent(content); mailTransport.sendMessage(msg, msg.getAllRecipients()); }
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: * ?/* ww w . j a v a 2s . c o m*/ * 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:fsi_admin.JSmtpConn.java
private boolean prepareMsg(String FROM, String TO, String SUBJECT, String MIMETYPE, String BODY, StringBuffer msj, Properties props, Session session, MimeMessage mmsg, BodyPart messagebodypart, MimeMultipart multipart) {/*w ww. jav a 2s. c om*/ // Create a message with the specified information. try { mmsg.setFrom(new InternetAddress(FROM)); mmsg.setRecipient(Message.RecipientType.TO, new InternetAddress(TO)); mmsg.setSubject(SUBJECT); messagebodypart.setContent(BODY, MIMETYPE); multipart.addBodyPart(messagebodypart); return true; } catch (AddressException e) { e.printStackTrace(); msj.append("Error de Direcciones al preparar SMTP: " + e.getMessage()); return false; } catch (MessagingException e) { e.printStackTrace(); msj.append("Error de Mensajeria al preparar SMTP: " + e.getMessage()); return false; } }
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.ja va2 s. com*/ * @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:com.email.SendEmailCalInvite.java
/** * Builds the calendar invite for the email * * @param eml EmailOutInvitesModel/*from w w w . j av a 2 s .c o m*/ * @return BodyPart (calendar invite) */ private static BodyPart inviteCalObject(EmailOutInvitesModel eml, SystemEmailModel account, String emailSubject) { BodyPart calendarPart = new MimeBodyPart(); try { String calendarContent = "BEGIN:VCALENDAR\n" + "METHOD:REQUEST\n" + "PRODID: BCP - Meeting\n" + "VERSION:2.0\n" + "BEGIN:VEVENT\n" + "DTSTAMP:" + Global.getiCalendarDateFormat().format(eml.getHearingStartTime()) + "\n" + "DTSTART:" + Global.getiCalendarDateFormat().format(eml.getHearingStartTime()) + "\n" + "DTEND:" + Global.getiCalendarDateFormat().format(eml.getHearingEndTime()) + "\n" //Subject + "SUMMARY:" + emailSubject.replace("Upcoming", "").trim() + "\n" + "UID:" + Calendar.getInstance().get(Calendar.MILLISECOND) + "\n" //return email + "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:" + new InternetAddress(account.getEmailAddress()).getAddress() + "\n" //return email + "ORGANIZER:MAILTO:" + new InternetAddress(account.getEmailAddress()).getAddress() + "\n" //hearing room + "LOCATION: " + eml.getHearingRoomAbv() + "\n" //subject + "DESCRIPTION: " + emailSubject + "\n" + "SEQUENCE:0\n" + "PRIORITY:5\n" + "CLASS:PUBLIC\n" + "STATUS:CONFIRMED\n" + "TRANSP:OPAQUE\n" + "BEGIN:VALARM\n" + "ACTION:DISPLAY\n" + "DESCRIPTION:REMINDER\n" + "TRIGGER;RELATED=START:-PT00H15M00S\n" + "END:VALARM\n" + "END:VEVENT\n" + "END:VCALENDAR"; calendarPart.addHeader("Content-Class", "urn:content-classes:calendarmessage"); calendarPart.setContent(calendarContent, "text/calendar;method=CANCEL"); } catch (MessagingException ex) { ExceptionHandler.Handle(ex); } return calendarPart; }