List of usage examples for javax.mail BodyPart setHeader
public void setHeader(String header_name, String header_value) throws MessagingException;
From source file:com.mgmtp.jfunk.core.reporting.EmailReporter.java
private void sendMessage(final String content) { try {//from w w w . jav a 2s . c o m MimeMessage msg = new MimeMessage(sessionProvider.get()); msg.setSubject("jFunk E-mail Report"); msg.addRecipients(Message.RecipientType.TO, recipientsProvider.get()); BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(content, "text/html; charset=UTF-8"); MimeMultipart multipart = new MimeMultipart("related"); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("check.gif"))); messageBodyPart.setHeader("Content-ID", "<check>"); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("error.gif"))); messageBodyPart.setHeader("Content-ID", "<error>"); multipart.addBodyPart(messageBodyPart); msg.setContent(multipart); smtpClientProvider.get().send(msg); int anzahlRecipients = msg.getAllRecipients().length; log.info( "Report e-mail was sent to " + anzahlRecipients + " recipient(s): " + recipientsProvider.get()); } catch (MessagingException e) { log.error("Error while creating report e-mail", e); } catch (MailException e) { log.error("Error while sending report e-mail", e); } }
From source file:io.mapzone.arena.share.app.EMailSharelet.java
private void sendEmail(final String toText, final String subjectText, final String messageText, final boolean withAttachment, final ImagePngContent image) throws Exception { MimeMessage msg = new MimeMessage(mailSession()); msg.addRecipients(RecipientType.TO, InternetAddress.parse(toText, false)); // TODO we need the FROM from the current user msg.addFrom(InternetAddress.parse("support@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) ); msg.setReplyTo(InternetAddress.parse("DO_NOT_REPLY_TO_THIS_EMAIL@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) ); msg.setSubject(subjectText, "utf-8"); if (withAttachment) { // add mime multiparts Multipart multipart = new MimeMultipart(); BodyPart part = new MimeBodyPart(); part.setText(messageText);/*from ww w . j a va2s. co m*/ multipart.addBodyPart(part); // Second part is attachment part = new MimeBodyPart(); part.setDataHandler(new DataHandler(new URLDataSource(new URL(image.imgResource)))); part.setFileName("preview.png"); part.setHeader("Content-ID", "preview"); multipart.addBodyPart(part); // // third part in HTML with embedded image // part = new MimeBodyPart(); // part.setContent( "<img src='cid:preview'>", "text/html" ); // multipart.addBodyPart( part ); msg.setContent(multipart); } else { msg.setText(messageText, "utf-8"); } msg.setSentDate(new Date()); Transport.send(msg); }
From source file:fr.paris.lutece.portal.service.mail.MailUtil.java
/** * Send a Multipart HTML message with the attachements associated to the * message and attached files. FIXME: use prepareMessage method * * @param strRecipientsTo/*from w ww . j a v a2 s. c om*/ * The list of the main recipients email.Every recipient must be * separated by the mail separator defined in config.properties * @param strRecipientsCc * The recipients list of the carbon copies . * @param strRecipientsBcc * The recipients list of the blind carbon copies . * @param strSenderName * The sender name. * @param strSenderEmail * The sender email address. * @param strSubject * The message subject. * @param strMessage * The message. * @param urlAttachements * The List of UrlAttachement Object, containing the URL of * attachments associated with their content-location. * @param fileAttachements * The list of files attached * @param transport * the smtp transport object * @param session * the smtp session object * @throws AddressException * If invalid address * @throws SendFailedException * If an error occured during sending * @throws MessagingException * If a messaging error occurred */ protected static void sendMultipartMessageHtml(String strRecipientsTo, String strRecipientsCc, String strRecipientsBcc, String strSenderName, String strSenderEmail, String strSubject, String strMessage, List<UrlAttachment> urlAttachements, List<FileAttachment> fileAttachements, Transport transport, Session session) throws MessagingException, AddressException, SendFailedException { Message msg = prepareMessage(strRecipientsTo, strRecipientsCc, strRecipientsBcc, strSenderName, strSenderEmail, strSubject, session); msg.setHeader(HEADER_NAME, HEADER_VALUE); // Creation of the root part containing all the elements of the message MimeMultipart multipart = ((fileAttachements == null) || (fileAttachements.isEmpty())) ? new MimeMultipart(MULTIPART_RELATED) : new MimeMultipart(); // Creation of the html part, the "core" of the message BodyPart msgBodyPart = new MimeBodyPart(); // msgBodyPart.setContent( strMessage, BODY_PART_MIME_TYPE ); msgBodyPart.setDataHandler(new DataHandler( new ByteArrayDataSource(strMessage, AppPropertiesService.getProperty(PROPERTY_MAIL_TYPE_HTML) + AppPropertiesService.getProperty(PROPERTY_CHARSET)))); multipart.addBodyPart(msgBodyPart); if (urlAttachements != null) { ByteArrayDataSource urlByteArrayDataSource; for (UrlAttachment urlAttachement : urlAttachements) { urlByteArrayDataSource = convertUrlAttachmentDataSourceToByteArrayDataSource(urlAttachement); if (urlByteArrayDataSource != null) { msgBodyPart = new MimeBodyPart(); // Fill this part, then add it to the root part with the // good headers msgBodyPart.setDataHandler(new DataHandler(urlByteArrayDataSource)); msgBodyPart.setHeader(HEADER_CONTENT_LOCATION, urlAttachement.getContentLocation()); multipart.addBodyPart(msgBodyPart); } } } // add File Attachement if (fileAttachements != null) { for (FileAttachment fileAttachement : fileAttachements) { String strFileName = fileAttachement.getFileName(); byte[] bContentFile = fileAttachement.getData(); String strContentType = fileAttachement.getType(); ByteArrayDataSource dataSource = new ByteArrayDataSource(bContentFile, strContentType); msgBodyPart = new MimeBodyPart(); msgBodyPart.setDataHandler(new DataHandler(dataSource)); msgBodyPart.setFileName(strFileName); msgBodyPart.setDisposition(CONSTANT_DISPOSITION_ATTACHMENT); multipart.addBodyPart(msgBodyPart); } } msg.setContent(multipart); sendMessage(msg, transport); }
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 a 2 s .co m * @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.nokia.helium.core.EmailDataSender.java
/** * Send xml data/* w w w .jav a2s . c o m*/ * * @param String purpose of this email * @param String file to send * @param String mime type * @param String subject of email * @param String header of mail * @param boolean compress data if true */ public void sendData(String purpose, File fileToSend, String mimeType, String subject, String header, boolean compressData) throws EmailSendException { try { log.debug("sendData:Send file: " + fileToSend + " and mimetype: " + mimeType); if (fileToSend != null && fileToSend.exists()) { InternetAddress[] toAddresses = getToAddressList(); Properties props = new Properties(); if (smtpServerAddress != null) { log.debug("sendData:smtp address: " + smtpServerAddress); props.setProperty("mail.smtp.host", smtpServerAddress); } Session mailSession = Session.getDefaultInstance(props, null); MimeMessage message = new MimeMessage(mailSession); message.setSubject(subject == null ? "" : subject); MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); ByteArrayDataSource dataSrc = null; String fileName = fileToSend.getName(); if (compressData) { log.debug("Sending compressed data"); dataSrc = compressFile(fileToSend); dataSrc.setName(fileName + ".gz"); messageBodyPart.setFileName(fileName + ".gz"); } else { log.debug("Sending uncompressed data:"); dataSrc = new ByteArrayDataSource(new FileInputStream(fileToSend), mimeType); message.setContent(FileUtils.readFileToString(fileToSend), "text/html"); multipart = null; } String headerToSend = null; if (header == null) { headerToSend = ""; } messageBodyPart.setHeader("helium-bld-data", headerToSend); messageBodyPart.setDataHandler(new DataHandler(dataSrc)); if (multipart != null) { multipart.addBodyPart(messageBodyPart); // add to the // multipart message.setContent(multipart); } try { message.setFrom(getFromAddress()); } catch (AddressException e) { throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e); } catch (LDAPException e) { throw new EmailSendException("Error retrieving the from address: " + e.getMessage(), e); } message.addRecipients(Message.RecipientType.TO, toAddresses); log.info("Sending email alert: " + subject); Transport.send(message); } } catch (MessagingException e) { String fullErrorMessage = "Failed sending e-mail: " + purpose; if (e.getMessage() != null) { fullErrorMessage += ": " + e.getMessage(); } throw new EmailSendException(fullErrorMessage, e); } catch (IOException e) { String fullErrorMessage = "Failed sending e-mail: " + purpose; if (e.getMessage() != null) { fullErrorMessage += ": " + e.getMessage(); } // We are Ignoring the errors as no need to fail the build. throw new EmailSendException(fullErrorMessage, e); } }
From source file:com.aurel.track.util.emailHandling.MailBuilder.java
private void includeImageLogo(MimeMultipart mimeMultipart) { BodyPart messageBodyPart; ArrayList<String> imageFiles = new ArrayList<String>(); imageFiles.add("tracklogo.gif"); // more images can be added here ArrayList<String> cids = new ArrayList<String>(); cids.add("logo"); // for each image there should be a cid here URL imageURL = null;/*ww w . j ava 2 s. c o m*/ for (int i = 0; i < imageFiles.size(); ++i) { try { DataSource ds = null; messageBodyPart = new MimeBodyPart(); InputStream in = null; in = ImageAction.class.getClassLoader().getResourceAsStream(imageFiles.get(i)); int length = imageFiles.get(i).length(); String type = imageFiles.get(i).substring(length - 4, length - 1); if (in != null) { ds = new ByteArrayDataSource(in, "image/" + type); System.err.println(type); } else { String theResource = "/WEB-INF/classes/resources/MailTemplates/" + imageFiles.get(i); imageURL = servletContext.getResource(theResource); ds = new URLDataSource(imageURL); } messageBodyPart.setDataHandler(new DataHandler(ds)); messageBodyPart.setHeader("Content-ID", cids.get(i)); messageBodyPart.setDisposition("inline"); // add it mimeMultipart.addBodyPart(messageBodyPart); } catch (Exception e) { LOGGER.error(ExceptionUtils.getStackTrace(e)); // what shall we do here? } } }
From source file:com.warsaw.data.controller.LoginController.java
private Message buildEmail(Session session, String to) throws Exception { Message message = new MimeMessage(session); message.setFrom(new InternetAddress(EMAIL)); // Set To: header field of the header. message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to)); // Set Subject: header field message.setSubject("Testing Subject"); // This mail has 2 part, the BODY and the embedded image MimeMultipart multipart = new MimeMultipart("related"); // first part (the html) BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = "<img style='width:800px' src=\"cid:image1\"><br/>" + "Dzie dobry,<br/><br/>" + "witamy na portalu TrasyPoWarszawsku.pl, na ktrym zostalo " + "zaoone konto<br/> dla osoby o danych: Jan Marian Ptak. W celu zakoczenia procesu tworzenia " + "konta prosimy uy linku aktywacyjnego:<br/><br/>" + "<a href='https://test.puesc.gov.pl?link=Gkhh&%JK.'>https://test.puesc.gov.pl?link=Gkhh&%JK.</a><br/><br/>" + "Na wywietlonym ekranie prosz wprowadzi zdefiniowane przez siebie haso awaryjne. Po prawidowym" + " wprowadzeniu danych<br/> oraz ustawieniu nowego hasa dostpowego konto na portalu PUESC zostanie aktywowane.<br/>" + "Link aktywacyjny pozostanie wany przez 24 godziny od momentu otrzymania niniejszej wiadomoci.<br/><br/>" + "<img style='width:800px' src=\"cid:image2\"><br/><br/>" + "Z powaaniem<br/><br/>" + "Zesp portalu PUESC<br/>" + "puesc@mofnet.gov.pl<br/>" + "<a href='http://puesc.gov.pl'>http://puesc.gov.pl</a>"; messageBodyPart.setContent(htmlText, "text/html; charset=ISO-8859-2"); // add it/*from ww w. ja va 2s . c o m*/ multipart.addBodyPart(messageBodyPart); // second part (the image) messageBodyPart = new MimeBodyPart(); DataSource fds = new FileDataSource("C:\\Users\\Pawel\\Desktop\\header.png"); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID", "<image1>"); // add image to the multipart multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); // URL url = new URL("http://ns3342351.ovh.net:8080/seap_lf_graphicsLayout_theme/images/refresh.png"); // URLDataSource fds1 =new URLDataSource(url); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID", "<image2>"); multipart.addBodyPart(messageBodyPart); // put everything together message.setContent(multipart); ByteArrayOutputStream b = new ByteArrayOutputStream(); try { message.writeTo(b); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return message; }
From source file:immf.MyHtmlEmail.java
/** * @throws EmailException EmailException * @throws MessagingException MessagingException *///from w w w . ja v a2 s .c om private void build() throws MessagingException, EmailException { MimeMultipart rootContainer = this.getContainer(); MimeMultipart bodyEmbedsContainer = rootContainer; MimeMultipart bodyContainer = rootContainer; BodyPart msgHtml = null; BodyPart msgText = null; rootContainer.setSubType("mixed"); // determine how to form multiparts of email if (StringUtils.isNotEmpty(this.html) && this.inlineEmbeds.size() > 0) { //If HTML body and embeds are used, create a related container and add it to the root container bodyEmbedsContainer = new MimeMultipart("related"); bodyContainer = bodyEmbedsContainer; this.addPart(bodyEmbedsContainer, 0); //If TEXT body was specified, create a alternative container and add it to the embeds container if (StringUtils.isNotEmpty(this.text)) { bodyContainer = new MimeMultipart("alternative"); BodyPart bodyPart = createBodyPart(); try { bodyPart.setContent(bodyContainer); bodyEmbedsContainer.addBodyPart(bodyPart, 0); } catch (MessagingException me) { throw new EmailException(me); } } } else if (StringUtils.isNotEmpty(this.text) && StringUtils.isNotEmpty(this.html)) { //If both HTML and TEXT bodies are provided, create a alternative container and add it to the root container bodyContainer = new MimeMultipart("alternative"); this.addPart(bodyContainer, 0); } if (StringUtils.isNotEmpty(this.html)) { msgHtml = new MimeBodyPart(); bodyContainer.addBodyPart(msgHtml, 0); // apply default charset if one has been set if (StringUtils.isNotEmpty(this.charset)) { msgHtml.setContent(this.html, Email.TEXT_HTML + "; charset=" + this.charset); } else { msgHtml.setContent(this.html, Email.TEXT_HTML); } if (contentTransferEncoding != null) { msgHtml.setHeader("Content-Transfer-Encoding", contentTransferEncoding); } Iterator<InlineImage> iter = this.inlineEmbeds.values().iterator(); while (iter.hasNext()) { InlineImage ii = (InlineImage) iter.next(); bodyEmbedsContainer.addBodyPart(ii.getMbp()); } } if (StringUtils.isNotEmpty(this.text)) { msgText = new MimeBodyPart(); bodyContainer.addBodyPart(msgText, 0); // apply default charset if one has been set if (StringUtils.isNotEmpty(this.charset)) { msgText.setContent(this.text, Email.TEXT_PLAIN + "; charset=" + this.charset); } else { msgText.setContent(this.text, Email.TEXT_PLAIN); } if (contentTransferEncoding != null) { msgText.setHeader("Content-Transfer-Encoding", contentTransferEncoding); } } }
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 w ww . j av 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.camel.component.mail.MailBinding.java
protected String populateContentOnBodyPart(BodyPart part, MailConfiguration configuration, Exchange exchange) throws MessagingException, IOException { String contentType = determineContentType(configuration, exchange); if (LOG.isTraceEnabled()) { LOG.trace("Using Content-Type " + contentType + " for BodyPart: " + part); }/* ww w . ja v a2 s . co m*/ // always store content in a byte array data store to avoid various content type and charset issues DataSource ds = new ByteArrayDataSource(exchange.getIn().getBody(String.class), contentType); part.setDataHandler(new DataHandler(ds)); // set the content type header afterwards part.setHeader("Content-Type", contentType); return contentType; }