List of usage examples for javax.mail.internet MimeMultipart MimeMultipart
public MimeMultipart(DataSource ds) throws MessagingException
From source file:org.snopoke.util.Emailer.java
public void send() throws MessagingException { notNull(from, "From address can not be null"); isTrue(!to.isEmpty() || !bcc.isEmpty(), "No TO or BCC addresses specified"); MimeMessage message = getMessasge(); // Cover wrap MimeBodyPart wrap = new MimeBodyPart(); MimeMultipart cover = getCoverPart(); wrap.setContent(cover);/*from w ww . j ava2s . c om*/ MimeMultipart content = new MimeMultipart("related"); message.setContent(content); content.addBodyPart(wrap); addAttachments(content); Transport.send(message); }
From source file:com.fiveamsolutions.nci.commons.util.MailUtils.java
/** * Send an email.//from ww w . j a v a 2s.co m * @param u the recipient of the message * @param title the subject of the message * @param html the html content of the message * @param plainText the plain text content of the message * @throws MessagingException on error. */ public static void sendEmail(AbstractUser u, String title, String html, String plainText) throws MessagingException { if (!isMailEnabled()) { LOG.info("sending email to " + u.getEmail() + " with title " + title); LOG.info("plain text: " + plainText); LOG.info("html: " + html); return; } MimeMessage msg = new MimeMessage(getMailSession()); msg.setFrom(new InternetAddress(getFromAddress())); msg.setRecipient(Message.RecipientType.TO, new InternetAddress(u.getEmail())); msg.setSubject(title); Multipart mp = new MimeMultipart("alternative"); BodyPart bp = new MimeBodyPart(); bp.setContent(html, "text/html"); mp.addBodyPart(bp); bp = new MimeBodyPart(); bp.setContent(plainText, "text/plain"); mp.addBodyPart(bp); msg.setContent(mp); Transport.send(msg); }
From source file:org.linagora.linshare.core.service.impl.MailNotifierServiceImpl.java
@Override public void sendNotification(String smtpSender, String replyTo, String recipient, String subject, String htmlContent, String inReplyTo, String references) throws SendFailedException { if (smtpServer.equals("")) { logger.warn("Mail notifications are disabled."); return;/* w w w . ja v a 2s. com*/ } // get the mail session Session session = getMailSession(); // Define message MimeMessage messageMim = new MimeMessage(session); try { messageMim.setFrom(new InternetAddress(smtpSender)); if (replyTo != null) { InternetAddress reply[] = new InternetAddress[1]; reply[0] = new InternetAddress(replyTo); messageMim.setReplyTo(reply); } messageMim.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient)); if (inReplyTo != null && inReplyTo != "") { // This field should contain only ASCCI character (RFC 822) if (isPureAscii(inReplyTo)) { messageMim.setHeader("In-Reply-To", inReplyTo); } } if (references != null && references != "") { // This field should contain only ASCCI character (RFC 822) if (isPureAscii(references)) { messageMim.setHeader("References", references); } } messageMim.setSubject(subject, charset); // Create a "related" Multipart message // content type is multipart/alternative // it will contain two part BodyPart 1 and 2 Multipart mp = new MimeMultipart("alternative"); // BodyPart 2 // content type is multipart/related // A multipart/related is used to indicate that message parts should // not be considered individually but rather // as parts of an aggregate whole. The message consists of a root // part (by default, the first) which reference other parts inline, // which may in turn reference other parts. Multipart html_mp = new MimeMultipart("related"); // Include an HTML message with images. // BodyParts: the HTML file and an image // Get the HTML file BodyPart rel_bph = new MimeBodyPart(); rel_bph.setDataHandler( new DataHandler(new ByteArrayDataSource(htmlContent, "text/html; charset=" + charset))); html_mp.addBodyPart(rel_bph); // Create the second BodyPart of the multipart/alternative, // set its content to the html multipart, and add the // second bodypart to the main multipart. BodyPart alt_bp2 = new MimeBodyPart(); alt_bp2.setContent(html_mp); mp.addBodyPart(alt_bp2); messageMim.setContent(mp); // RFC 822 "Date" header field // Indicates that the message is complete and ready for delivery messageMim.setSentDate(new GregorianCalendar().getTime()); // Since we used html tags, the content must be marker as text/html // messageMim.setContent(content,"text/html; charset="+charset); Transport tr = session.getTransport("smtp"); // Connect to smtp server, if needed if (needsAuth) { tr.connect(smtpServer, smtpPort, smtpUser, smtpPassword); messageMim.saveChanges(); tr.sendMessage(messageMim, messageMim.getAllRecipients()); tr.close(); } else { // Send message Transport.send(messageMim); } } catch (SendFailedException e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort + " to " + recipient, e); throw e; } catch (MessagingException e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e); throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e); } catch (Exception e) { logger.error("Error sending notification on " + smtpServer + " port " + smtpPort, e); throw new TechnicalException(TechnicalErrorCode.MAIL_EXCEPTION, "Error sending notification", e); } }
From source file:org.tizzit.util.mail.MailHelper.java
/** * Send an email in html-format in iso-8859-1-encoding * //from w w w .ja va 2s. c om * @param subject the subject of the new mail * @param htmlMessage the content of the mail as html * @param alternativeTextMessage the content of the mail as text * @param from the sender-address * @param to the receiver-address * @param cc the address of the receiver of a copy of this mail * @param bcc the address of the receiver of a blind-copy of this mail */ public static void sendHtmlMail2(String subject, String htmlMessage, String alternativeTextMessage, String from, String to, String cc, String bcc) { try { MimeMessage msg = new MimeMessage(mailSession); msg.setFrom(new InternetAddress(from)); if (cc != null && !cc.equals("")) msg.setRecipients(Message.RecipientType.CC, cc); if (bcc != null && !bcc.equals("")) msg.setRecipients(Message.RecipientType.BCC, bcc); msg.addRecipients(Message.RecipientType.TO, to); msg.setSubject(subject, "ISO8859_1"); msg.setSentDate(new Date()); MimeMultipart multiPart = new MimeMultipart("alternative"); MimeBodyPart htmlPart = new MimeBodyPart(); MimeBodyPart textPart = new MimeBodyPart(); textPart.setText(alternativeTextMessage, "ISO8859_1"); textPart.setHeader("MIME-Version", "1.0"); //textPart.setHeader("Content-Type", textPart.getContentType()); textPart.setHeader("Content-Type", "text/plain;charset=\"ISO-8859-1\""); htmlPart.setContent(htmlMessage, "text/html;charset=\"ISO8859_1\""); htmlPart.setHeader("MIME-Version", "1.0"); htmlPart.setHeader("Content-Type", "text/html;charset=\"ISO-8859-1\""); //htmlPart.setHeader("Content-Type", htmlPart.getContentType()); multiPart.addBodyPart(textPart); multiPart.addBodyPart(htmlPart); multiPart.setSubType("alternative"); msg.setContent(multiPart); msg.setHeader("MIME-Version", "1.0"); msg.setHeader("Content-Type", multiPart.getContentType()); Transport.send(msg); } catch (Exception e) { log.error("Error sending html-mail: " + e.getLocalizedMessage()); } }
From source file:ste.xtest.mail.BugFreeFileTransport.java
@Test public void send_multipart_message() throws Exception { Session session = Session.getInstance(config); Message message = new MimeMessage(Session.getInstance(config)); message.setFrom(new InternetAddress("from@domain.com")); message.addRecipient(Message.RecipientType.TO, new InternetAddress("to@domain.com")); message.setSubject("the subject"); MimeMultipart multipart = new MimeMultipart("related"); BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = "<H1>hello world</H1><img src=\"cid:image\">"; messageBodyPart.setContent(htmlText, "text/html"); multipart.addBodyPart(messageBodyPart); messageBodyPart = new MimeBodyPart(); DataSource fds = new FileDataSource("src/test/resources/images/6096.png"); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID", "<image>"); multipart.addBodyPart(messageBodyPart); message.setContent(multipart);// w ww. j a va 2 s . c o m session.getTransport().sendMessage(message, message.getAllRecipients()); then(FileUtils.readFileToString(new File(TMP.getRoot(), "message"))).contains("From: from@domain.com\r") .contains("To: to@domain.com\r").contains("Subject: the subject\r").contains("hello world") .contains("Content-ID: <image>"); }
From source file:com.nokia.helium.core.EmailDataSender.java
/** * Send xml data//from www .j a v a 2 s.co 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:lucee.runtime.net.mail.HtmlEmailImpl.java
/** * @throws EmailException EmailException * @throws MessagingException MessagingException *///from w w w. j a v a2s . c om 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:org.entermedia.email.PostMail.java
public void postMail(List<InternetAddress> recipients, List<InternetAddress> blindrecipients, String subject, String inHtml, String inText, String from, List inAttachments, Map inProperties) throws MessagingException { // Set the host smtp address Properties props = new Properties(); // create some properties and get the default Session props.put("mail.smtp.host", fieldSmtpServer); props.put("mail.smtp.port", String.valueOf(getPort())); props.put("mail.smtp.auth", new Boolean(fieldSmtpSecured).toString()); if (isSslEnabled()) { props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); }//from w w w.jav a 2s.c o m Session session = null; if (isEnableTls()) { props.put("mail.smtp.starttls.enable", "true"); session = Session.getInstance(props, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(getSmtpUsername(), getSmtpPassword()); } }); } else if (fieldSmtpSecured) { SmtpAuthenticator auth = new SmtpAuthenticator(); session = Session.getInstance(props, auth); } else { session = Session.getInstance(props); } // session.setDebug(debug); // create a message Message msg = new MimeMessage(session); MimeMultipart mp = null; // msg.setDataHandler(new DataHandler(new ByteArrayDataSource(message, // "text/html"))); if (inAttachments != null && inAttachments.size() == 0) { inAttachments = null; } if (inText != null && inHtml != null || inAttachments != null) { // Create an "Alternative" Multipart message mp = new MimeMultipart("mixed"); if (inText != null) { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(inText, "text/plain"); mp.addBodyPart(messageBodyPart); } if (inHtml != null) { BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setContent(inHtml, "text/html"); mp.addBodyPart(messageBodyPart); } if (inAttachments != null) { for (Iterator iterator = inAttachments.iterator(); iterator.hasNext();) { String filename = (String) iterator.next(); File file = new File(filename); if (file.exists() && !file.isDirectory()) { // create the second message part MimeBodyPart mbp = new MimeBodyPart(); FileDataSource fds = new FileDataSource(file); mbp.setDataHandler(new DataHandler(fds)); mbp.setFileName(fds.getName()); mp.addBodyPart(mbp); } } } msg.setContent(mp); } else if (inHtml != null) { msg.setContent(inHtml, "text/html"); } else { msg.setContent(inText, "text/plain"); } // set the from and to address InternetAddress addressFrom = new InternetAddress(from); msg.setFrom(addressFrom); //msg.setRecipient(RecipientType.BCC, addressFrom); msg.setSentDate(new Date()); if (recipients == null || recipients.isEmpty()) { throw new MessagingException("No recipients specified"); } InternetAddress[] addressTo = recipients.toArray(new InternetAddress[recipients.size()]); msg.setRecipients(Message.RecipientType.TO, addressTo); //add bcc if (blindrecipients != null && !blindrecipients.isEmpty()) { InternetAddress[] addressBcc = blindrecipients.toArray(new InternetAddress[blindrecipients.size()]); msg.setRecipients(Message.RecipientType.BCC, addressBcc); } // Optional : You can also set your custom headers in the Email if you // Want // msg.addHeader("MyHeaderName", "myHeaderValue"); // Setting the Subject and Content Type msg.setSubject(subject); // Transport tr = session.getTransport("smtp"); // tr.connect(serverandport[0], null, null); // msg.saveChanges(); // don't forget this // tr.sendMessage(msg, msg.getAllRecipients()); // tr.close(); // msg.setContent(msg, "text/plain"); Transport.send(msg); log.info("sent email " + subject); }
From source file:org.snopoke.util.Emailer.java
private MimeMultipart getCoverPart() throws MessagingException { // Alternative TEXT/HTML content MimeMultipart cover = new MimeMultipart("alternative"); if (textContent != null && !textContent.isEmpty()) { MimeBodyPart text = new MimeBodyPart(); cover.addBodyPart(text);//from www. j av a 2 s. c om text.setText(textContent); } if (htmlContent != null && !htmlContent.isEmpty()) { MimeBodyPart html = new MimeBodyPart(); cover.addBodyPart(html); html.setContent(htmlContent, "text/html"); } return cover; }
From source file:com.linkedin.r2.message.rest.QueryTunnelUtil.java
/** * Takes a Request object that has been encoded for tunnelling as a POST with an X-HTTP-Override-Method header and * creates a new request that represents the intended original request * * @param request the request to be decoded * @param requestContext a RequestContext object associated with the request * * @return a decoded RestRequest// ww w.j av a 2 s .c o m */ public static RestRequest decode(final RestRequest request, RequestContext requestContext) throws MessagingException, IOException, URISyntaxException { if (request.getHeader(HEADER_METHOD_OVERRIDE) == null) { // Not a tunnelled request, just pass thru return request; } String query = null; byte[] entity = new byte[0]; // All encoded requests must have a content type. If the header is missing, ContentType throws an exception ContentType contentType = new ContentType(request.getHeader(HEADER_CONTENT_TYPE)); RestRequestBuilder requestBuilder = request.builder(); // Get copy of headers and remove the override Map<String, String> h = new HashMap<String, String>(request.getHeaders()); h.remove(HEADER_METHOD_OVERRIDE); // Simple case, just extract query params from entity, append to query, and clear entity if (contentType.getBaseType().equals(FORM_URL_ENCODED)) { query = request.getEntity().asString(Data.UTF_8_CHARSET); h.remove(HEADER_CONTENT_TYPE); h.remove(CONTENT_LENGTH); } else if (contentType.getBaseType().equals(MULTIPART)) { // Clear these in case there is no body part h.remove(HEADER_CONTENT_TYPE); h.remove(CONTENT_LENGTH); MimeMultipart multi = new MimeMultipart(new DataSource() { @Override public InputStream getInputStream() throws IOException { return request.getEntity().asInputStream(); } @Override public OutputStream getOutputStream() throws IOException { return null; } @Override public String getContentType() { return request.getHeader(HEADER_CONTENT_TYPE); } @Override public String getName() { return null; } }); for (int i = 0; i < multi.getCount(); i++) { MimeBodyPart part = (MimeBodyPart) multi.getBodyPart(i); if (part.isMimeType(FORM_URL_ENCODED) && query == null) { // Assume the first segment we come to that is urlencoded is the tunneled query params query = IOUtils.toString((InputStream) part.getContent(), UTF8); } else if (entity.length <= 0) { // Assume the first non-urlencoded content we come to is the intended entity. Object content = part.getContent(); if (content instanceof MimeMultipart) { ByteArrayOutputStream os = new ByteArrayOutputStream(); ((MimeMultipart) content).writeTo(os); entity = os.toByteArray(); } else { entity = IOUtils.toByteArray((InputStream) content); } h.put(CONTENT_LENGTH, Integer.toString(entity.length)); h.put(HEADER_CONTENT_TYPE, part.getContentType()); } else { // If it's not form-urlencoded and we've already found another section, // this has to be be an extra body section, which we have no way to handle. // Proceed with the request as if the 1st part we found was the expected body, // but log a warning in case some client is constructing a request that doesn't // follow the rules. String unexpectedContentType = part.getContentType(); LOG.warn("Unexpected body part in X-HTTP-Method-Override request, type=" + unexpectedContentType); } } } // Based on what we've found, construct the modified request. It's possible that someone has // modified the request URI, adding extra query params for debugging, tracking, etc, so // we have to check and append the original query correctly. if (query != null && query.length() > 0) { String separator = "&"; String existingQuery = request.getURI().getRawQuery(); if (existingQuery == null) { separator = "?"; } else if (existingQuery.isEmpty()) { // This would mean someone has appended a "?" with no args to the url underneath us separator = ""; } requestBuilder.setURI(new URI(request.getURI().toString() + separator + query)); } requestBuilder.setEntity(entity); requestBuilder.setHeaders(h); requestBuilder.setMethod(request.getHeader(HEADER_METHOD_OVERRIDE)); requestContext.putLocalAttr(R2Constants.IS_QUERY_TUNNELED, true); return requestBuilder.build(); }