Search in sources :

Example 21 with MimeMessage

use of javax.mail.internet.MimeMessage in project jodd by oblac.

the class SendMailSession method createMessage.

// ---------------------------------------------------------------- adapter
/**
	 * Creates new JavaX message from {@link Email email}.
	 */
protected MimeMessage createMessage(Email email, Session session) throws MessagingException {
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(email.getFrom().toInternetAddress());
    // to
    int totalTo = email.getTo().length;
    InternetAddress[] address = new InternetAddress[totalTo];
    for (int i = 0; i < totalTo; i++) {
        address[i] = email.getTo()[i].toInternetAddress();
    }
    msg.setRecipients(Message.RecipientType.TO, address);
    // replyTo
    if (email.getReplyTo() != null) {
        int totalReplyTo = email.getReplyTo().length;
        address = new InternetAddress[totalReplyTo];
        for (int i = 0; i < totalReplyTo; i++) {
            address[i] = email.getReplyTo()[i].toInternetAddress();
        }
        msg.setReplyTo(address);
    }
    // cc
    if (email.getCc() != null) {
        int totalCc = email.getCc().length;
        address = new InternetAddress[totalCc];
        for (int i = 0; i < totalCc; i++) {
            address[i] = email.getCc()[i].toInternetAddress();
        }
        msg.setRecipients(Message.RecipientType.CC, address);
    }
    // bcc
    if (email.getBcc() != null) {
        int totalBcc = email.getBcc().length;
        address = new InternetAddress[totalBcc];
        for (int i = 0; i < totalBcc; i++) {
            address[i] = email.getBcc()[i].toInternetAddress();
        }
        msg.setRecipients(Message.RecipientType.BCC, address);
    }
    if (email.getSubjectEncoding() != null) {
        msg.setSubject(email.getSubject(), email.getSubjectEncoding());
    } else {
        msg.setSubject(email.getSubject());
    }
    Date date = email.getSentDate();
    if (date == null) {
        date = new Date();
    }
    msg.setSentDate(date);
    // headers
    Map<String, String> headers = email.getAllHeaders();
    if (headers != null) {
        for (Map.Entry<String, String> stringStringEntry : headers.entrySet()) {
            String value = stringStringEntry.getValue();
            msg.setHeader(stringStringEntry.getKey(), value);
        }
    }
    // message data and attachments
    final List<EmailMessage> messages = email.getAllMessages();
    final List<EmailAttachment> attachments = email.getAttachments() == null ? null : new ArrayList<>(email.getAttachments());
    final int totalMessages = messages.size();
    if ((attachments == null) && (totalMessages == 1)) {
        // special case: no attachments and just one content
        EmailMessage emailMessage = messages.get(0);
        msg.setContent(emailMessage.getContent(), emailMessage.getMimeType() + CHARSET + emailMessage.getEncoding());
    } else {
        Multipart multipart = new MimeMultipart();
        Multipart msgMultipart = multipart;
        if (totalMessages > 1) {
            MimeBodyPart bodyPart = new MimeBodyPart();
            msgMultipart = new MimeMultipart(ALTERNATIVE);
            bodyPart.setContent(msgMultipart);
            multipart.addBodyPart(bodyPart);
        }
        for (EmailMessage emailMessage : messages) {
            // detect embedded attachments
            List<EmailAttachment> embeddedAttachments = filterEmbeddedAttachments(attachments, emailMessage);
            MimeBodyPart bodyPart = new MimeBodyPart();
            if (embeddedAttachments == null) {
                // no embedded attachments, just add message
                bodyPart.setContent(emailMessage.getContent(), emailMessage.getMimeType() + CHARSET + emailMessage.getEncoding());
            } else {
                // embedded attachments detected, join them as related
                MimeMultipart relatedMultipart = new MimeMultipart(RELATED);
                MimeBodyPart messageData = new MimeBodyPart();
                messageData.setContent(emailMessage.getContent(), emailMessage.getMimeType() + CHARSET + emailMessage.getEncoding());
                relatedMultipart.addBodyPart(messageData);
                for (EmailAttachment att : embeddedAttachments) {
                    MimeBodyPart attBodyPart = createAttachmentBodyPart(att);
                    relatedMultipart.addBodyPart(attBodyPart);
                }
                bodyPart.setContent(relatedMultipart);
            }
            msgMultipart.addBodyPart(bodyPart);
        }
        if (attachments != null) {
            // attach remaining attachments
            for (EmailAttachment att : attachments) {
                MimeBodyPart attBodyPart = createAttachmentBodyPart(att);
                multipart.addBodyPart(attBodyPart);
            }
        }
        msg.setContent(multipart);
    }
    return msg;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) Date(java.util.Date) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Map(java.util.Map)

Example 22 with MimeMessage

use of javax.mail.internet.MimeMessage in project Axe by DongyuCai.

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)

Example 23 with MimeMessage

use of javax.mail.internet.MimeMessage in project Smartcity-Smarthouse by TechnionYP5777.

the class Communicate method throughEmail.

/**
     * based on:
     * http://www.javatpoint.com/example-of-sending-email-using-java-mail-api-through-gmail-server
     * 
     * @param a
     *            an Authentactor of the fromMail email address param
     * @return a string representing the state of the request, or null if the
     *         request failed
     */
public static String throughEmail(final String fromMail, final Authenticator a, final String $, final String msg) {
    final Properties properties = System.getProperties();
    properties.put("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.socketFactory.port", "465");
    properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    properties.put("mail.smtp.auth", "true");
    properties.put("mail.smtp.port", "465");
    final Session session = Session.getDefaultInstance(properties, a);
    try {
        final MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromMail));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress($));
        message.setSubject("SmartHouse Alert!");
        message.setText(msg);
        // Send message
        Transport.send(message);
    } catch (final MessagingException mex) {
        log.error("A messaging error occurred", mex);
        return null;
    }
    return "The e-mail was sent to:" + $;
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) Properties(java.util.Properties) Session(javax.mail.Session)

Example 24 with MimeMessage

use of javax.mail.internet.MimeMessage in project Activiti by Activiti.

the class EmailServiceTaskTest method assertEmailSend.

// Helper 
public static void assertEmailSend(WiserMessage emailMessage, boolean htmlMail, String subject, String message, String from, List<String> to, List<String> cc) throws IOException {
    try {
        MimeMessage mimeMessage = emailMessage.getMimeMessage();
        System.out.println(mimeMessage.getContentType());
        if (htmlMail) {
            assertTrue(mimeMessage.getContentType().contains("multipart/mixed"));
        } else {
            assertTrue(mimeMessage.getContentType().contains("text/plain"));
        }
        assertEquals(subject, mimeMessage.getHeader("Subject", null));
        assertEquals(from, mimeMessage.getHeader("From", null));
        assertTrue(getMessage(mimeMessage).contains(message));
        for (String t : to) {
            assertTrue(mimeMessage.getHeader("To", null).contains(t));
        }
        if (cc != null) {
            for (String c : cc) {
                assertTrue(mimeMessage.getHeader("Cc", null).contains(c));
            }
        }
    } catch (MessagingException e) {
        fail(e.getMessage());
    }
}
Also used : MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException)

Example 25 with MimeMessage

use of javax.mail.internet.MimeMessage in project nhin-d by DirectProject.

the class DirectBounce method service.

/**
	 * {@inheritDoc}
	 */
@Override
public void service(Mail mail) throws MessagingException {
    final MimeMessage msg = mail.getMessage();
    final NHINDAddressCollection recipients = getMailRecipients(mail);
    final NHINDAddress sender = getMailSender(mail);
    final Tx txToTrack = getTxToTrack(msg, sender, recipients);
    // create a DSN message
    if (txToTrack != null && txToTrack.getMsgType() == TxMessageType.IMF)
        this.sendDSN(txToTrack, recipients, false);
}
Also used : NHINDAddress(org.nhindirect.stagent.NHINDAddress) Tx(org.nhindirect.common.tx.model.Tx) MimeMessage(javax.mail.internet.MimeMessage) NHINDAddressCollection(org.nhindirect.stagent.NHINDAddressCollection)

Aggregations

MimeMessage (javax.mail.internet.MimeMessage)1146 Test (org.junit.Test)374 InternetAddress (javax.mail.internet.InternetAddress)334 MessagingException (javax.mail.MessagingException)299 Session (javax.mail.Session)222 Properties (java.util.Properties)219 MimeMultipart (javax.mail.internet.MimeMultipart)208 MimeBodyPart (javax.mail.internet.MimeBodyPart)178 Date (java.util.Date)153 IOException (java.io.IOException)137 Message (javax.mail.Message)120 MimeMessageHelper (org.springframework.mail.javamail.MimeMessageHelper)107 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)97 ZMimeMessage (com.zimbra.common.zmime.ZMimeMessage)83 InputStream (java.io.InputStream)82 ArrayList (java.util.ArrayList)81 Multipart (javax.mail.Multipart)75 DataHandler (javax.activation.DataHandler)73 ByteArrayOutputStream (java.io.ByteArrayOutputStream)72 BodyPart (javax.mail.BodyPart)70