Search in sources :

Example 26 with Multipart

use of javax.mail.Multipart in project xwiki-platform by xwiki.

the class ResetPasswordIT method getMessageContent.

protected Map<String, String> getMessageContent(MimeMessage message) throws Exception {
    Map<String, String> messageMap = new HashMap<String, String>();
    Address[] addresses = message.getAllRecipients();
    Assert.assertTrue(addresses.length == 1);
    messageMap.put("recipient", addresses[0].toString());
    messageMap.put("subjectLine", message.getSubject());
    Multipart mp = (Multipart) message.getContent();
    BodyPart plain = getPart(mp, "text/plain");
    if (plain != null) {
        messageMap.put("textPart", IOUtils.toString(plain.getInputStream()));
    }
    BodyPart html = getPart(mp, "text/html");
    if (html != null) {
        messageMap.put("htmlPart", IOUtils.toString(html.getInputStream()));
    }
    return messageMap;
}
Also used : BodyPart(javax.mail.BodyPart) Multipart(javax.mail.Multipart) Address(javax.mail.Address) HashMap(java.util.HashMap)

Example 27 with Multipart

use of javax.mail.Multipart in project xwiki-platform by xwiki.

the class MailSenderPlugin method createMimeMultipart.

/**
 * Creates a Multipart MIME Message (multiple content-types within the same message) from an existing mail
 *
 * @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));
        }
        // 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;
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) Pattern(java.util.regex.Pattern) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) MimeMultipart(javax.mail.internet.MimeMultipart) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) Attachment(com.xpn.xwiki.api.Attachment) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 28 with Multipart

use of javax.mail.Multipart in project xwiki-platform by xwiki.

the class MailSenderPlugin method createMimeMessage.

/**
 * Creates a MIME message (message with binary content carrying capabilities) from an existing Mail
 *
 * @param mail The original Mail object
 * @param session Mail session
 * @return The MIME message
 */
private MimeMessage createMimeMessage(Mail mail, Session session, XWikiContext context) throws MessagingException, XWikiException, IOException {
    // this will also check for email error
    InternetAddress from = new InternetAddress(mail.getFrom());
    String recipients = mail.getHeader("To");
    if (StringUtils.isBlank(recipients)) {
        recipients = mail.getTo();
    } else {
        recipients = mail.getTo() + "," + recipients;
    }
    InternetAddress[] to = toInternetAddresses(recipients);
    recipients = mail.getHeader("Cc");
    if (StringUtils.isBlank(recipients)) {
        recipients = mail.getCc();
    } else {
        recipients = mail.getCc() + "," + recipients;
    }
    InternetAddress[] cc = toInternetAddresses(recipients);
    recipients = mail.getHeader("Bcc");
    if (StringUtils.isBlank(recipients)) {
        recipients = mail.getBcc();
    } else {
        recipients = mail.getBcc() + "," + recipients;
    }
    InternetAddress[] bcc = toInternetAddresses(recipients);
    if ((to == null) && (cc == null) && (bcc == null)) {
        LOGGER.info("No recipient -> skipping this email");
        return null;
    }
    MimeMessage message = new MimeMessage(session);
    message.setSentDate(new Date());
    message.setFrom(from);
    if (to != null) {
        message.setRecipients(javax.mail.Message.RecipientType.TO, to);
    }
    if (cc != null) {
        message.setRecipients(javax.mail.Message.RecipientType.CC, cc);
    }
    if (bcc != null) {
        message.setRecipients(javax.mail.Message.RecipientType.BCC, bcc);
    }
    message.setSubject(mail.getSubject(), EMAIL_ENCODING);
    for (Map.Entry<String, String> header : mail.getHeaders().entrySet()) {
        message.setHeader(header.getKey(), header.getValue());
    }
    if (mail.getHtmlPart() != null || mail.getAttachments() != null) {
        Multipart multipart = createMimeMultipart(mail, context);
        message.setContent(multipart);
    } else {
        message.setText(mail.getTextPart());
    }
    message.setSentDate(new Date());
    message.saveChanges();
    return message;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) MimeMessage(javax.mail.internet.MimeMessage) Map(java.util.Map) Date(java.util.Date)

Example 29 with Multipart

use of javax.mail.Multipart in project JFramework by gugumall.

the class SendMailTask method doSend.

/**
 * @param to 收件人
 * @param cc 抄送
 * @param subj 标题
 * @param text 正文
 * @param type 邮件正文内容类型,text/html或text/plain
 * @param encoding 邮件正文内容字符编码
 * @param filePaths 邮件附件的文件路径[]
 * @return
 */
public boolean doSend(String to, String cc, String subj, String text, String type, String encoding, String[] filePaths, String fromName) {
    try {
        if (to == null || to.indexOf("@") < 1) {
            throw new Exception("no valid recipient!");
        }
        String[] tos = to.split(",");
        boolean recipientsValid = true;
        for (int i = 0; i < tos.length; i++) {
            tos[i] = tos[i].trim();
            if (!JUtilString.isEmail(tos[i], 64)) {
                recipientsValid = false;
                break;
            }
        }
        if (!recipientsValid) {
            throw new Exception("there are some invalid recipients!");
        }
        if (cc != null && cc.indexOf("@") > 0) {
            String[] ccs = to.split(",");
            boolean ccsValid = true;
            for (int i = 0; i < ccs.length; i++) {
                ccs[i] = ccs[i].trim();
                if (!JUtilString.isEmail(ccs[i], 64)) {
                    ccsValid = false;
                    break;
                }
            }
            if (!ccsValid) {
                throw new Exception("there are some invalid cc recipients!");
            }
        }
        if (filePaths != null && filePaths.length > 0) {
            boolean filesExist = true;
            for (int i = 0; i < filePaths.length; i++) {
                File file = new File(filePaths[i]);
                if (!file.exists() || !file.isFile()) {
                    file = null;
                    filesExist = false;
                    break;
                } else {
                    file = null;
                }
            }
            if (!filesExist) {
                throw new Exception("there are some files non exist or is not a file!");
            }
        }
        Properties props = new Properties();
        props.put("mail.smtp.host", config.getHost());
        props.put("mail.smtp.port", config.getPort());
        props.put("mail.smtp.auth", "true");
        if (config.getSecure()) {
            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.smtp.socketFactory.port", config.getPort());
        }
        Authentication auth = new Authentication(config.getUser(), config.getPassword());
        Session session = Session.getInstance(props, auth);
        session.setDebug(false);
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(config.getFrom()));
        String nick = fromName;
        if (nick == null)
            nick = config.getFromName();
        if (nick != null && !"".equals(nick)) {
            nick = javax.mail.internet.MimeUtility.encodeText(nick);
            msg.setFrom(new InternetAddress(nick + " <" + config.getFrom() + ">"));
        }
        InternetAddress[] toAddrs = InternetAddress.parse(to, false);
        msg.setRecipients(Message.RecipientType.TO, toAddrs);
        Multipart mp = new MimeMultipart();
        // 正文
        if (text != null) {
            MimeBodyPart mbp = new MimeBodyPart();
            if (MailSender.CONTENT_HTML.equals(type)) {
                if (encoding == null || encoding.equals(""))
                    mbp.setContent(text, "text/html; charset=" + SysConfig.sysEncoding);
                else
                    mbp.setContent(text, "text/html; charset=" + encoding);
            } else {
                if (encoding == null || encoding.equals(""))
                    mbp.setContent(text, "text/plain; charset=" + SysConfig.sysEncoding);
                else
                    mbp.setContent(text, "text/plain; charset=" + encoding);
            }
            mp.addBodyPart(mbp);
        }
        // 附件
        if (filePaths != null && filePaths.length > 0) {
            for (int i = 0; i < filePaths.length; i++) {
                File file = new File(filePaths[i]);
                if (file.exists() && file.canRead()) {
                    // 如果附件存在且可读
                    MimeBodyPart mbp = new MimeBodyPart();
                    FileDataSource fds = new FileDataSource(file.getAbsolutePath());
                    mbp.setDataHandler(new DataHandler(fds));
                    mbp.setFileName(file.getName());
                    mp.addBodyPart(mbp);
                }
            }
        }
        msg.setContent(mp);
        InternetAddress[] ccAddrs = null;
        if (cc != null && cc.indexOf("@") > 0) {
            ccAddrs = null;
            ccAddrs = InternetAddress.parse(cc, false);
            msg.setRecipients(Message.RecipientType.CC, ccAddrs);
        }
        if (subj != null) {
            msg.setSubject(subj);
        }
        msg.setSentDate(new Date());
        msg.saveChanges();
        Transport.send(msg);
        return true;
    } catch (Exception e) {
        log.log(e.getMessage(), Logger.LEVEL_ERROR);
        return false;
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) JUtilString(j.util.JUtilString) DataHandler(javax.activation.DataHandler) Properties(java.util.Properties) Date(java.util.Date) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File) Session(javax.mail.Session)

Example 30 with Multipart

use of javax.mail.Multipart in project tesb-rt-se by Talend.

the class MailSender method createMultipart.

private Multipart createMultipart(String message, URL attachment) throws MessagingException {
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText(message);
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(messageBodyPart);
    messageBodyPart = new MimeBodyPart();
    DataSource source = new URLDataSource(attachment);
    messageBodyPart.setDataHandler(new DataHandler(source));
    multipart.addBodyPart(messageBodyPart);
    return multipart;
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) URLDataSource(javax.activation.URLDataSource) MimeMultipart(javax.mail.internet.MimeMultipart) DataHandler(javax.activation.DataHandler) MimeBodyPart(javax.mail.internet.MimeBodyPart) URLDataSource(javax.activation.URLDataSource) DataSource(javax.activation.DataSource)

Aggregations

Multipart (javax.mail.Multipart)140 MimeMultipart (javax.mail.internet.MimeMultipart)101 MimeBodyPart (javax.mail.internet.MimeBodyPart)87 MimeMessage (javax.mail.internet.MimeMessage)79 BodyPart (javax.mail.BodyPart)60 InternetAddress (javax.mail.internet.InternetAddress)59 MessagingException (javax.mail.MessagingException)54 Session (javax.mail.Session)42 DataHandler (javax.activation.DataHandler)40 Properties (java.util.Properties)34 IOException (java.io.IOException)33 Date (java.util.Date)29 Message (javax.mail.Message)28 FileDataSource (javax.activation.FileDataSource)26 DataSource (javax.activation.DataSource)23 InputStream (java.io.InputStream)22 File (java.io.File)21 Part (javax.mail.Part)19 Test (org.junit.Test)16 UnsupportedEncodingException (java.io.UnsupportedEncodingException)10