Search in sources :

Example 1 with MimeMultipart

use of javax.mail.internet.MimeMultipart in project camel by apache.

the class MailBinding method extractHeadersFromMail.

protected Map<String, Object> extractHeadersFromMail(Message mailMessage, Exchange exchange) throws MessagingException, IOException {
    Map<String, Object> answer = new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);
    Enumeration<?> names = mailMessage.getAllHeaders();
    while (names.hasMoreElements()) {
        Header header = (Header) names.nextElement();
        String value = header.getValue();
        if (headerFilterStrategy != null && !headerFilterStrategy.applyFilterToExternalHeaders(header.getName(), value, exchange)) {
            CollectionHelper.appendValue(answer, header.getName(), value);
        }
    }
    // if the message is a multipart message, do not set the content type to multipart/*
    if (((MailEndpoint) exchange.getFromEndpoint()).getConfiguration().isMapMailMessage()) {
        Object content = mailMessage.getContent();
        if (content instanceof MimeMultipart) {
            MimeMultipart multipart = (MimeMultipart) content;
            int size = multipart.getCount();
            for (int i = 0; i < size; i++) {
                BodyPart part = multipart.getBodyPart(i);
                content = part.getContent();
                // in case of nested multiparts iterate into them
                while (content instanceof MimeMultipart) {
                    if (multipart.getCount() < 1) {
                        break;
                    }
                    part = ((MimeMultipart) content).getBodyPart(0);
                    content = part.getContent();
                }
                if (part.getContentType().toLowerCase().startsWith("text")) {
                    answer.put(Exchange.CONTENT_TYPE, part.getContentType());
                    break;
                }
            }
        }
    }
    return answer;
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) Header(javax.mail.Header) MimeMultipart(javax.mail.internet.MimeMultipart) TreeMap(java.util.TreeMap)

Example 2 with MimeMultipart

use of javax.mail.internet.MimeMultipart in project camel by apache.

the class MailBinding method createMultipartAlternativeMessage.

protected void createMultipartAlternativeMessage(MimeMessage mimeMessage, MailConfiguration configuration, Exchange exchange) throws MessagingException, IOException {
    MimeMultipart multipartAlternative = new MimeMultipart("alternative");
    mimeMessage.setContent(multipartAlternative);
    MimeBodyPart plainText = new MimeBodyPart();
    plainText.setText(getAlternativeBody(configuration, exchange), determineCharSet(configuration, exchange));
    // remove the header with the alternative mail now that we got it
    // otherwise it might end up twice in the mail reader
    exchange.getIn().removeHeader(configuration.getAlternativeBodyHeader());
    multipartAlternative.addBodyPart(plainText);
    // if there are no attachments, add the body to the same mulitpart message
    if (!exchange.getIn().hasAttachments()) {
        addBodyToMultipart(configuration, multipartAlternative, exchange);
    } else {
        // treat them as normal. It will append a multipart-mixed with the attachments and the body text
        if (!configuration.isUseInlineAttachments()) {
            BodyPart mixedAttachments = new MimeBodyPart();
            mixedAttachments.setContent(createMixedMultipartAttachments(configuration, exchange));
            multipartAlternative.addBodyPart(mixedAttachments);
        } else {
            // if the attachments are set to be inline, attach them as inline attachments
            MimeMultipart multipartRelated = new MimeMultipart("related");
            BodyPart related = new MimeBodyPart();
            related.setContent(multipartRelated);
            multipartAlternative.addBodyPart(related);
            addBodyToMultipart(configuration, multipartRelated, exchange);
            AttachmentsContentTransferEncodingResolver resolver = configuration.getAttachmentsContentTransferEncodingResolver();
            addAttachmentsToMultipart(multipartRelated, Part.INLINE, resolver, exchange);
        }
    }
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 3 with MimeMultipart

use of javax.mail.internet.MimeMultipart in project Openfire by igniterealtime.

the class EmailService method sendMessage.

/**
     * Sends a message, specifying all of its fields.<p>
     *
     * To have more advanced control over the message sent, use the
     * {@link #sendMessage(MimeMessage)} method.<p>
     *
     * Both a plain text and html body can be specified. If one of the values is null,
     * only the other body type is sent. If both body values are set, a multi-part
     * message will be sent. If parts of the message are invalid (ie, the toEmail is null)
     * the message won't be sent.
     *
     * @param toName the name of the recipient of this email.
     * @param toEmail the email address of the recipient of this email.
     * @param fromName the name of the sender of this email.
     * @param fromEmail the email address of the sender of this email.
     * @param subject the subject of the email.
     * @param textBody plain text body of the email, which can be <tt>null</tt> if the
     *      html body is not null.
     * @param htmlBody html body of the email, which can be <tt>null</tt> if the text body
     *      is not null.
     */
public void sendMessage(String toName, String toEmail, String fromName, String fromEmail, String subject, String textBody, String htmlBody) {
    // Check for errors in the given fields:
    if (toEmail == null || fromEmail == null || subject == null || (textBody == null && htmlBody == null)) {
        Log.error("Error sending email: Invalid fields: " + ((toEmail == null) ? "toEmail " : "") + ((fromEmail == null) ? "fromEmail " : "") + ((subject == null) ? "subject " : "") + ((textBody == null && htmlBody == null) ? "textBody or htmlBody " : ""));
    } else {
        try {
            String encoding = MimeUtility.mimeCharset("UTF-8");
            MimeMessage message = createMimeMessage();
            Address to;
            Address from;
            if (toName != null) {
                to = new InternetAddress(toEmail, toName, encoding);
            } else {
                to = new InternetAddress(toEmail, "", encoding);
            }
            if (fromName != null) {
                from = new InternetAddress(fromEmail, fromName, encoding);
            } else {
                from = new InternetAddress(fromEmail, "", encoding);
            }
            // Set the date of the message to be the current date
            SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", java.util.Locale.US);
            format.setTimeZone(JiveGlobals.getTimeZone());
            message.setHeader("Date", format.format(new Date()));
            message.setHeader("Content-Transfer-Encoding", "8bit");
            message.setRecipient(Message.RecipientType.TO, to);
            message.setFrom(from);
            message.setSubject(StringUtils.replace(subject, "\n", ""), encoding);
            // Create HTML, plain-text, or combination message
            if (textBody != null && htmlBody != null) {
                MimeMultipart content = new MimeMultipart("alternative");
                // Plain-text
                MimeBodyPart text = new MimeBodyPart();
                text.setText(textBody, encoding);
                text.setDisposition(Part.INLINE);
                content.addBodyPart(text);
                // HTML
                MimeBodyPart html = new MimeBodyPart();
                html.setContent(htmlBody, "text/html; charset=UTF-8");
                html.setDisposition(Part.INLINE);
                html.setHeader("Content-Transfer-Encoding", "8bit");
                content.addBodyPart(html);
                // Add multipart to message.
                message.setContent(content);
                message.setDisposition(Part.INLINE);
                sendMessage(message);
            } else if (textBody != null) {
                MimeBodyPart bPart = new MimeBodyPart();
                bPart.setText(textBody, encoding);
                bPart.setDisposition(Part.INLINE);
                bPart.setHeader("Content-Transfer-Encoding", "8bit");
                MimeMultipart mPart = new MimeMultipart();
                mPart.addBodyPart(bPart);
                message.setContent(mPart);
                message.setDisposition(Part.INLINE);
                // Add the message to the send list
                sendMessage(message);
            } else if (htmlBody != null) {
                MimeBodyPart bPart = new MimeBodyPart();
                bPart.setContent(htmlBody, "text/html; charset=UTF-8");
                bPart.setDisposition(Part.INLINE);
                bPart.setHeader("Content-Transfer-Encoding", "8bit");
                MimeMultipart mPart = new MimeMultipart();
                mPart.addBodyPart(bPart);
                message.setContent(mPart);
                message.setDisposition(Part.INLINE);
                // Add the message to the send list
                sendMessage(message);
            }
        } catch (Exception e) {
            Log.error(e.getMessage(), e);
        }
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date) AddressException(javax.mail.internet.AddressException) MessagingException(javax.mail.MessagingException) SendFailedException(javax.mail.SendFailedException)

Example 4 with MimeMultipart

use of javax.mail.internet.MimeMultipart in project Openfire by igniterealtime.

the class SendMail method sendMessage.

public boolean sendMessage(String message, String host, String port, String username, String password) {
    boolean ok = false;
    String uidString = "";
    try {
        // Set the email properties necessary to send email
        final Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.server", host);
        if (ModelUtil.hasLength(port)) {
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", port);
        }
        Session sess;
        if (ModelUtil.hasLength(password) && ModelUtil.hasLength(username)) {
            sess = Session.getInstance(props, new MailAuthentication(username, password));
        } else {
            sess = Session.getDefaultInstance(props, null);
        }
        Message msg = new MimeMessage(sess);
        StringTokenizer toST = new StringTokenizer(toField, ",");
        if (toST.countTokens() > 1) {
            InternetAddress[] address = new InternetAddress[toST.countTokens()];
            int addrIndex = 0;
            String addrString = "";
            while (toST.hasMoreTokens()) {
                addrString = toST.nextToken();
                address[addrIndex] = (new InternetAddress(addrString));
                addrIndex = addrIndex + 1;
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        } else {
            InternetAddress[] address = { new InternetAddress(toField) };
            msg.setRecipients(Message.RecipientType.TO, address);
        }
        InternetAddress from = new InternetAddress(myAddress);
        msg.setFrom(from);
        msg.setSubject(subjectField);
        UID msgUID = new UID();
        uidString = msgUID.toString();
        msg.setHeader("X-Mailer", uidString);
        msg.setSentDate(new Date());
        MimeMultipart mp = new MimeMultipart();
        // create body part for textarea
        MimeBodyPart mbp1 = new MimeBodyPart();
        if (getCustomerName() != null) {
            messageText = "From: " + getCustomerName() + "\n" + messageText;
        }
        if (isHTML) {
            mbp1.setContent(messageText, "text/html");
        } else {
            mbp1.setContent(messageText, "text/plain");
        }
        mp.addBodyPart(mbp1);
        try {
            if (!isHTML) {
                msg.setContent(messageText, "text/plain");
            } else {
                msg.setContent(messageText, "text/html");
            }
            Transport.send(msg);
            ok = true;
        } catch (SendFailedException sfe) {
            Log.warn("Could not connect to SMTP server.");
        }
    } catch (Exception eq) {
        Log.warn("Could not connect to SMTP server.");
    }
    return ok;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) SendFailedException(javax.mail.SendFailedException) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Properties(java.util.Properties) Date(java.util.Date) SendFailedException(javax.mail.SendFailedException) UID(java.rmi.server.UID) StringTokenizer(java.util.StringTokenizer) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session)

Example 5 with MimeMultipart

use of javax.mail.internet.MimeMultipart in project KJFrameForAndroid by kymjs.

the class SimpleMailSender method sendHtmlMail.

/**
     * 以HTML格式发送邮件
     * 
     * @param mailInfo
     *            待发送的邮件信息
     */
public static boolean sendHtmlMail(MailSenderInfo mailInfo) {
    // 判断是否需要身份认证
    MyAuthenticator authenticator = null;
    Properties pro = mailInfo.getProperties();
    // 如果需要身份认证,则创建一个密码验证器
    if (mailInfo.isValidate()) {
        authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
    }
    // 根据邮件会话属性和密码验证器构造一个发送邮件的session
    Session sendMailSession = Session.getDefaultInstance(pro, authenticator);
    try {
        // 根据session创建一个邮件消息
        Message mailMessage = new MimeMessage(sendMailSession);
        // 创建邮件发送者地址
        Address from = new InternetAddress(mailInfo.getFromAddress());
        // 设置邮件消息的发送者
        mailMessage.setFrom(from);
        // 创建邮件的接收者地址,并设置到邮件消息中
        Address to = new InternetAddress(mailInfo.getToAddress());
        // Message.RecipientType.TO属性表示接收者的类型为TO
        mailMessage.setRecipient(Message.RecipientType.TO, to);
        // 设置邮件消息的主题
        mailMessage.setSubject(mailInfo.getSubject());
        // 设置邮件消息发送的时间
        mailMessage.setSentDate(new Date());
        // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
        Multipart mainPart = new MimeMultipart();
        // 创建一个包含HTML内容的MimeBodyPart
        BodyPart html = new MimeBodyPart();
        // 设置HTML内容
        html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        // 将MiniMultipart对象设置为邮件内容
        mailMessage.setContent(mainPart);
        // 发送邮件
        Transport.send(mailMessage);
        return true;
    } catch (MessagingException ex) {
        ex.printStackTrace();
    }
    return false;
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) Message(javax.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) Address(javax.mail.Address) InternetAddress(javax.mail.internet.InternetAddress) MessagingException(javax.mail.MessagingException) Properties(java.util.Properties) Date(java.util.Date) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Session(javax.mail.Session)

Aggregations

MimeMultipart (javax.mail.internet.MimeMultipart)188 MimeBodyPart (javax.mail.internet.MimeBodyPart)114 MimeMessage (javax.mail.internet.MimeMessage)71 MessagingException (javax.mail.MessagingException)65 BodyPart (javax.mail.BodyPart)51 ByteArrayOutputStream (java.io.ByteArrayOutputStream)49 IOException (java.io.IOException)45 ByteString (com.linkedin.data.ByteString)37 Test (org.testng.annotations.Test)31 ZMimeMultipart (com.zimbra.common.zmime.ZMimeMultipart)27 InternetAddress (javax.mail.internet.InternetAddress)27 ZMimeBodyPart (com.zimbra.common.zmime.ZMimeBodyPart)26 HashMap (java.util.HashMap)25 DataHandler (javax.activation.DataHandler)25 Multipart (javax.mail.Multipart)21 ByteArrayDataSource (javax.mail.util.ByteArrayDataSource)19 InputStream (java.io.InputStream)18 Date (java.util.Date)17 ByteArrayInputStream (java.io.ByteArrayInputStream)16 Properties (java.util.Properties)16