List of usage examples for javax.mail.internet MimeBodyPart MimeBodyPart
public MimeBodyPart()
From source file:se.inera.axel.shs.processor.ShsMessageMarshaller.java
public void marshal(ShsMessage shsMessage, OutputStream outputStream) throws IllegalMessageStructureException { log.trace("marshal(ShsMessage, OutputStream)"); MimeMultipart multipart = new MimeMultipart(); BodyPart bodyPart = new MimeBodyPart(); try {//from ww w .j av a 2s .com ShsLabel label = shsMessage.getLabel(); if (label == null) { throw new IllegalMessageStructureException("label not found in shs message"); } Content content = label.getContent(); if (content == null) { throw new IllegalMessageStructureException("label/content not found in shs label"); } else { // we will update this according to our data parts below. content.getDataOrCompound().clear(); String contentId = content.getContentId(); content.setContentId(contentId.substring(0, Math.min(contentId.length(), MAX_LENGTH_CONTENT_ID))); } List<DataPart> dataParts = shsMessage.getDataParts(); if (dataParts.isEmpty()) { throw new IllegalMessageStructureException("dataparts not found in message"); } for (DataPart dp : dataParts) { Data data = new Data(); data.setDatapartType(dp.getDataPartType()); data.setFilename(dp.getFileName()); if (dp.getContentLength() != null && dp.getContentLength() > 0) data.setNoOfBytes("" + dp.getContentLength()); content.getDataOrCompound().add(data); } bodyPart.setContent(shsLabelMarshaller.marshal(label), "text/xml; charset=ISO-8859-1"); bodyPart.setHeader("Content-Transfer-Encoding", "binary"); multipart.addBodyPart(bodyPart); for (DataPart dataPart : dataParts) { bodyPart = new MimeBodyPart(); bodyPart.setDisposition(Part.ATTACHMENT); if (StringUtils.isNotBlank(dataPart.getFileName())) { bodyPart.setFileName(dataPart.getFileName()); } bodyPart.setDataHandler(dataPart.getDataHandler()); if (dataPart.getTransferEncoding() != null) { bodyPart.addHeader("Content-Transfer-Encoding", dataPart.getTransferEncoding().toLowerCase()); } multipart.addBodyPart(bodyPart); } MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setSubject("SHS Message"); mimeMessage.addHeader("Content-Transfer-Encoding", "binary"); mimeMessage.setContent(multipart); mimeMessage.saveChanges(); String ignoreList[] = { "Message-ID" }; mimeMessage.writeTo(outputStream, ignoreList); outputStream.flush(); } catch (Exception e) { if (e instanceof IllegalMessageStructureException) { throw (IllegalMessageStructureException) e; } throw new IllegalMessageStructureException(e); } }
From source file:org.openmrs.module.reporting.report.processor.EmailReportProcessor.java
/** * Performs some action on the given report * @param report the Report to process/* w ww . java 2s.co m*/ */ public void process(Report report, Properties configuration) { try { Message m = new MimeMessage(getSession()); m.setFrom(new InternetAddress(configuration.getProperty("from"))); for (String recipient : configuration.getProperty("to", "").split("\\,")) { m.addRecipient(RecipientType.TO, new InternetAddress(recipient)); } // TODO: Make these such that they can contain report information m.setSubject(configuration.getProperty("subject")); Multipart multipart = new MimeMultipart(); MimeBodyPart contentBodyPart = new MimeBodyPart(); String content = configuration.getProperty("content", ""); if (report.getRenderedOutput() != null && "true".equalsIgnoreCase(configuration.getProperty("addOutputToContent"))) { content += new String(report.getRenderedOutput()); } contentBodyPart.setContent(content, "text/html"); multipart.addBodyPart(contentBodyPart); if (report.getRenderedOutput() != null && "true".equalsIgnoreCase(configuration.getProperty("addOutputAsAttachment"))) { MimeBodyPart attachment = new MimeBodyPart(); Object output = report.getRenderedOutput(); if (report.getOutputContentType().contains("text")) { output = new String(report.getRenderedOutput(), "UTF-8"); } attachment.setDataHandler(new DataHandler(output, report.getOutputContentType())); attachment.setFileName(configuration.getProperty("attachmentName")); multipart.addBodyPart(attachment); } m.setContent(multipart); Transport.send(m); } catch (Exception e) { throw new RuntimeException("Error occurred while sending report over email", e); } }
From source file:org.grouter.common.mail.MailHandler.java
/** * Creates a multipart email with html and plain text email body to fallback to if * email client do not handle html base emails. * * @param mimeMessage/*from w ww. j ava2s . c om*/ * @param dto * @throws MessagingException */ private void createHtmlAndPlainTextBody(MimeMessage mimeMessage, MailDto dto) throws MessagingException { if (StringUtils.isNotEmpty(dto.getHtmlTextBody())) { mimeMessage.setContentID(MailDto.CONTENT_TYPE_MULTIPART_ALTERNATIVE); // Create your text message part BodyPart plainBodyPart = new MimeBodyPart(); plainBodyPart.setContent(dto.getPlainTextBody(), MailDto.CONTENT_TYPE_TEXT_PLAIN); // Create a multi-part to combine the parts Multipart multipart = new MimeMultipart("alternative"); multipart.addBodyPart(plainBodyPart); StringBuilder sb = new StringBuilder(); sb.append(PRE_HTML_HEADER); sb.append(dto.getSubject()).append("\n"); sb.append(POST_HTML_HEADER); sb.append(dto.getHtmlTextBody()); sb.append(END_HTML); BodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(sb.toString(), MailDto.CONTENT_TYPE_TEXT_HTML); // Add html part to multi part multipart.addBodyPart(htmlBodyPart); mimeMessage.setContent(multipart); } else { mimeMessage.setSubject(dto.getSubject()); mimeMessage.setText(dto.getPlainTextBody()); mimeMessage.setContent(dto.getPlainTextBody(), MailDto.CONTENT_TYPE_TEXT_PLAIN); } }
From source file:org.codice.alliance.core.email.impl.EmailSenderImpl.java
/** sendEmail method sends email after receiving input parameters */ @Override/* w w w . j a v a2 s . c o m*/ public void sendEmail(String fromEmail, String toEmail, String subject, String body, List<Pair<String, InputStream>> attachments) throws IOException { notNull(fromEmail, "fromEmail must be non-null"); notNull(toEmail, "toEmail must be non-null"); notNull(subject, "subject must be non-null"); notNull(body, "body must be non-null"); notNull(attachments, "attachments must be non-null"); if (StringUtils.isBlank(mailHost)) { throw new IOException("the mail server hostname has not been configured"); } List<File> tempFiles = new LinkedList<>(); try { InternetAddress emailAddr = new InternetAddress(toEmail); emailAddr.validate(); Properties properties = createSessionProperties(); Session session = Session.getDefaultInstance(properties); MimeMessage mimeMessage = new MimeMessage(session); mimeMessage.setFrom(new InternetAddress(fromEmail)); mimeMessage.addRecipient(Message.RecipientType.TO, emailAddr); mimeMessage.setSubject(subject); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText(body); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); Holder<Long> bytesWritten = new Holder<>(0L); for (Pair<String, InputStream> attachment : attachments) { messageBodyPart = new MimeBodyPart(); File file = File.createTempFile("email-sender-", ".dat"); tempFiles.add(file); copyDataToTempFile(file, attachment.getValue(), bytesWritten); messageBodyPart.setDataHandler(new DataHandler(new FileDataSource(file))); messageBodyPart.setFileName(attachment.getKey()); multipart.addBodyPart(messageBodyPart); } mimeMessage.setContent(multipart); send(mimeMessage); LOGGER.debug("Email sent to " + toEmail); } catch (AddressException e) { throw new IOException("invalid email address: email=" + toEmail, e); } catch (MessagingException e) { throw new IOException("message error occurred on send", e); } finally { tempFiles.forEach(file -> { if (!file.delete()) { LOGGER.debug("unable to delete tmp file: path={}", file); } }); } }
From source file:com.tdclighthouse.commons.mail.util.MailClient.java
protected void addAtachments(String[] attachments, Multipart multipart) throws MessagingException, AddressException { for (int i = 0; i < attachments.length; i++) { String filename = attachments[i]; MimeBodyPart attachmentBodyPart = new MimeBodyPart(); // use a JAF FileDataSource as it does MIME type detection DataSource source = new FileDataSource(filename); attachmentBodyPart.setDataHandler(new DataHandler(source)); // assume that the filename you want to send is the same as the // actual file name - could alter this to remove the file path attachmentBodyPart.setFileName(filename); // add the attachment multipart.addBodyPart(attachmentBodyPart); }// ww w . jav a 2s .com }
From source file:fr.hoteia.qalingo.core.util.impl.MimeMessagePreparatorImpl.java
public void prepare(MimeMessage message) throws Exception { // AUTO unsubscribe for Gmail/Hotmail etc : RFC2369 if (StringUtils.isNotEmpty(getUnsubscribeUrlOrEmail())) { message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">"); }/* w w w . ja v a 2s . com*/ if (getFrom() != null) { List<InternetAddress> toAddress = new ArrayList<InternetAddress>(); toAddress.add(new InternetAddress(getFrom(), getFromName())); message.addFrom(toAddress.toArray(new InternetAddress[toAddress.size()])); } if (getTo() != null) { message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo())); } if (getCc() != null) { message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(getCc())); } if (getSubject() != null) { message.setSubject(getSubject()); } MimeMultipart mimeMultipart = new MimeMultipart("alternative");// multipart/mixed or mixed or related or alternative message.setContent(mimeMultipart); if (getPlainTextContent() != null) { BodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(getPlainTextContent(), "text/plain"); mimeMultipart.addBodyPart(textBodyPart); } if (getHtmlContent() != null) { BodyPart htmlBodyPart = new MimeBodyPart(); htmlBodyPart.setContent(getHtmlContent(), "text/html"); mimeMultipart.addBodyPart(htmlBodyPart); } }
From source file:at.molindo.notify.channel.mail.AbstractMailClient.java
@Override public synchronized void send(Dispatch dispatch) throws MailException { Message message = dispatch.getMessage(); String recipient = dispatch.getParams().get(MailChannel.RECIPIENT); String recipientName = dispatch.getParams().get(MailChannel.RECIPIENT_NAME); String subject = message.getSubject(); try {/*from w w w . j av a 2s . c o m*/ MimeMessage mm = new MimeMessage(getSmtpSession(recipient)) { @Override protected void updateMessageID() throws MessagingException { String domain = _from.getAddress(); int idx = _from.getAddress().indexOf('@'); if (idx >= 0) { domain = domain.substring(idx + 1); } setHeader("Message-ID", "<" + UUID.randomUUID() + "@" + domain + ">"); } }; mm.setFrom(_from); mm.setSender(_from); InternetAddress replyTo = getReplyTo(); if (replyTo != null) { mm.setReplyTo(new Address[] { replyTo }); } mm.setHeader("X-Mailer", "molindo-notify"); mm.setSentDate(new Date()); mm.setRecipient(RecipientType.TO, new InternetAddress(recipient, recipientName, CharsetUtils.UTF_8.displayName())); mm.setSubject(subject, CharsetUtils.UTF_8.displayName()); if (_format == Format.HTML) { if (message.getType() == Type.TEXT) { throw new MailException("can't send HTML mail from TEXT message", false); } mm.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html"); } else if (_format == Format.TEXT || _format == Format.MULTI && message.getType() == Type.TEXT) { mm.setText(message.getText(), CharsetUtils.UTF_8.displayName()); } else if (_format == Format.MULTI) { MimeBodyPart html = new MimeBodyPart(); html.setText(message.getHtml(), CharsetUtils.UTF_8.displayName(), "html"); MimeBodyPart text = new MimeBodyPart(); text.setText(message.getText(), CharsetUtils.UTF_8.displayName()); /* * The formats are ordered by how faithful they are to the * original, with the least faithful first and the most faithful * last. (http://en.wikipedia.org/wiki/MIME#Alternative) */ MimeMultipart mmp = new MimeMultipart(); mmp.setSubType("alternative"); mmp.addBodyPart(text); mmp.addBodyPart(html); mm.setContent(mmp); } else { throw new NotifyRuntimeException( "unexpected format (" + _format + ") or type (" + message.getType() + ")"); } send(mm); } catch (final MessagingException e) { throw new MailException( "could not send mail from " + _from + " to " + recipient + " (" + toErrorMessage(e) + ")", e, isTemporary(e)); } catch (UnsupportedEncodingException e) { throw new RuntimeException("utf8 unknown?", e); } }
From source file:com.jwm123.loggly.reporter.ReportMailer.java
public MimeBodyPart newMultipartBodyPart(Multipart multipart) throws MessagingException { MimeBodyPart mimeBodyPart = new MimeBodyPart(); mimeBodyPart.setContent(multipart);/*from ww w . jav a2s . c om*/ return mimeBodyPart; }
From source file:com.googlecode.psiprobe.tools.Mailer.java
private static MimeBodyPart createAttachmentPart(DataSource attachment) throws MessagingException { MimeBodyPart attachmentPart = new MimeBodyPart(); attachmentPart.setDataHandler(new DataHandler(attachment)); attachmentPart.setDisposition(MimeBodyPart.ATTACHMENT); attachmentPart.setFileName(attachment.getName()); return attachmentPart; }
From source file:com.email.SendEmailCalInvite.java
/** * Builds the calendar invite for the email * * @param eml EmailOutInvitesModel/*from w ww . j ava 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; }