Example usage for javax.mail.internet MimeMessage addHeader

List of usage examples for javax.mail.internet MimeMessage addHeader

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage addHeader.

Prototype

@Override
public void addHeader(String name, String value) throws MessagingException 

Source Link

Document

Add this value to the existing values for this header_name.

Usage

From source file:nl.surfnet.coin.teams.control.JoinTeamController.java

private void sendJoinTeamMessage(final Team team, final Person person, final String message,
        final Locale locale) throws IllegalStateException, IOException {

    Object[] subjectValues = { team.getName() };
    final String subject = messageSource.getMessage(REQUEST_MEMBERSHIP_SUBJECT, subjectValues, locale);

    final Set<Member> admins = grouperTeamService.findAdmins(team);
    if (CollectionUtils.isEmpty(admins)) {
        throw new RuntimeException("Team '" + team.getName() + "' has no admins to mail invites");
    }/* w ww  .j  a v  a2  s  . com*/

    final String html = composeJoinRequestMailMessage(team, person, message, locale, "html");
    final String plainText = composeJoinRequestMailMessage(team, person, message, locale, "plaintext");

    final List<InternetAddress> bcc = new ArrayList<InternetAddress>();
    for (Member admin : admins) {
        try {
            bcc.add(new InternetAddress(admin.getEmail()));
        } catch (AddressException ae) {
            log.debug("Admin has malformed email address", ae);
        }
    }
    if (bcc.isEmpty()) {
        throw new RuntimeException(
                "Team '" + team.getName() + "' has no admins with valid email addresses to mail invites");
    }

    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws MessagingException {
            mimeMessage.addHeader("Precedence", "bulk");

            mimeMessage.setFrom(new InternetAddress(environment.getSystemEmail()));
            mimeMessage.setRecipients(Message.RecipientType.BCC, bcc.toArray(new InternetAddress[bcc.size()]));
            mimeMessage.setSubject(subject);

            MimeMultipart rootMixedMultipart = controllerUtil.getMimeMultipartMessageBody(plainText, html);
            mimeMessage.setContent(rootMixedMultipart);
        }
    };

    mailService.sendAsync(preparator);

}

From source file:ee.cyber.licensing.service.MailService.java

public void generateAndSendMail(MailBody mailbody, int licenseId, int fileId)
        throws MessagingException, IOException, SQLException {
    License license = licenseRepository.findById(licenseId);
    List<Contact> contacts = contactRepository.findAll(license.getCustomer());
    List<String> receivers = getReceivers(mailbody, contacts);

    logger.info("1st ===> setup Mail Server Properties");
    Properties mailServerProperties = getProperties();

    final String email = mailServerProperties.getProperty("fromEmail");
    final String password = mailServerProperties.getProperty("password");
    final String host = mailServerProperties.getProperty("mail.smtp.host");

    logger.info("2nd ===> create Authenticator object to pass in Session.getInstance argument");

    Authenticator authentication = new Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(email, password);
        }/*w  w w  . j  av a  2  s  .com*/
    };
    logger.info("Mail Server Properties have been setup successfully");

    logger.info("3rd ===> get Mail Session..");
    Session getMailSession = Session.getInstance(mailServerProperties, authentication);

    logger.info("4th ===> generateAndSendEmail() starts");
    MimeMessage mailMessage = new MimeMessage(getMailSession);

    mailMessage.addHeader("Content-type", "text/html; charset=UTF-8");
    mailMessage.addHeader("format", "flowed");
    mailMessage.addHeader("Content-Transfer-Encoding", "8bit");

    mailMessage.setFrom(new InternetAddress(email, "License dude"));
    //mailMessage.setReplyTo(InternetAddress.parse(email, false));
    mailMessage.setSubject(mailbody.getSubject());
    //String emailBody = body + "<br><br> Regards, <br>Cybernetica team";
    mailMessage.setSentDate(new Date());

    for (String receiver : receivers) {
        mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(receiver));
    }

    if (fileId != 0) {
        MailAttachment file = fileRepository.findById(fileId);
        if (file != null) {
            String fileName = file.getFileName();
            byte[] fileData = file.getData_b();
            if (fileName != null) {
                // Create a multipart message for attachment
                Multipart multipart = new MimeMultipart();
                // Body part
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setContent(mailbody.getBody(), "text/html");
                multipart.addBodyPart(messageBodyPart);

                //Attachment part
                messageBodyPart = new MimeBodyPart();
                ByteArrayDataSource source = new ByteArrayDataSource(fileData, "application/octet-stream");
                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(fileName);
                multipart.addBodyPart(messageBodyPart);

                mailMessage.setContent(multipart);
            }
        }
    } else {
        mailMessage.setContent(mailbody.getBody(), "text/html");
    }

    logger.info("5th ===> Get Session");
    sendMail(email, password, host, getMailSession, mailMessage);
}

From source file:fr.hoteia.qalingo.core.util.impl.MimeMessagePreparatorImpl.java

public void prepare(MimeMessage message) throws Exception {

    // AUTO unsubscribe for Gmail/Hotmail etc : RFC2369
    if (StringUtils.isNotEmpty(getUnsubscribeUrlOrEmail())) {
        message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">");
    }/*from   www  .j  av a 2 s.c om*/

    if (getFrom() != null) {
        List<InternetAddress> toAddress = new ArrayList<InternetAddress>();
        toAddress.add(new InternetAddress(getFrom(), getFromName()));
        message.addFrom(toAddress.toArray(new InternetAddress[toAddress.size()]));
    }
    if (getTo() != null) {
        message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(getTo()));
    }
    if (getCc() != null) {
        message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(getCc()));
    }
    if (getSubject() != null) {
        message.setSubject(getSubject());
    }

    MimeMultipart mimeMultipart = new MimeMultipart("alternative");// multipart/mixed or mixed or related or alternative
    message.setContent(mimeMultipart);

    if (getPlainTextContent() != null) {
        BodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(getPlainTextContent(), "text/plain");
        mimeMultipart.addBodyPart(textBodyPart);
    }

    if (getHtmlContent() != null) {
        BodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(getHtmlContent(), "text/html");
        mimeMultipart.addBodyPart(htmlBodyPart);
    }

}

From source file:org.apache.james.transport.mailets.delivery.MailDispatcher.java

private Collection<MailAddress> deliver(Mail mail, MimeMessage message) {
    Collection<MailAddress> errors = new Vector<MailAddress>();
    for (MailAddress recipient : mail.getRecipients()) {
        try {//  w w w. jav a2 s. co  m
            // Add qmail's de facto standard Delivered-To header
            message.addHeader(DELIVERED_TO, recipient.toString());
            mailStore.storeMail(recipient, mail);
            message.removeHeader(DELIVERED_TO);
        } catch (Exception ex) {
            log.error("Error while storing mail.", ex);
            errors.add(recipient);
        }
    }
    return errors;
}

From source file:davmail.smtp.TestSmtp.java

public void testBrokenMessage2() throws MessagingException, IOException, InterruptedException {
    MimeMessage mimeMessage = new MimeMessage(null,
            new org.apache.commons.codec.binary.Base64InputStream(new FileInputStream("broken64.txt")));
    mimeMessage.addHeader("To", Settings.getProperty("davmail.to"));
    sendAndCheckMessage(mimeMessage);//from  w  w w. j  a va 2 s.c  o m
}

From source file:mitm.common.mail.MailUtilsTest.java

@Test
public void testUnknownCharsetAddHeader() throws IOException, MessagingException {
    MimeMessage message = loadMessage("unknown-charset.eml");

    message.addHeader("X-Test", "test");

    message.saveChanges();/*from ww  w  .j  a  v a2 s  . co m*/

    MailUtils.validateMessage(message);
}

From source file:mitm.common.mail.MailUtilsTest.java

@Test
public void testUnknownContentTypeAddHeader() throws IOException, MessagingException {
    MimeMessage message = loadMessage("unknown-content-type.eml");

    message.addHeader("X-Test", "test");

    message.saveChanges();/*from  ww w.  j a  v  a 2 s.  c o m*/

    MailUtils.validateMessage(message);
}

From source file:ar.com.zauber.commons.message.impl.mail.MimeEmailNotificationStrategy.java

/**
 * If message is a {@link HeaderMessage}, adds headers to the {@link MimeMessage}
 * @param message/*from w  w  w . j a v  a2s  .c  o m*/
 * @param mail
 * @throws UnsupportedEncodingException 
 * @throws MessagingException 
 */
private void addHeaders(final Message message, final MimeMessage mail)
        throws MessagingException, UnsupportedEncodingException {
    if (message instanceof HeaderMessage) {
        final Map<String, String> headers = ((HeaderMessage) message).getHeaders();
        for (final Entry<String, String> entry : headers.entrySet()) {
            mail.addHeader(entry.getKey(), MimeUtility.encodeText(entry.getValue()));
        }
    }
}

From source file:edu.washington.iam.tools.IamMailSender.java

private MimeMessage genMimeMessage(IamMailMessage msg) {
    MimeMessage mime = mailSender.createMimeMessage();
    try {/*from w  ww.  j  a  va 2  s.  c o  m*/
        mime.setRecipients(RecipientType.TO, InternetAddress.parse(msg.getTo()));
        mime.setSubject(msg.makeSubstitutions(msg.getSubject()));
        mime.setReplyTo(InternetAddress.parse(replyTo));
        mime.setFrom(new InternetAddress(msg.getFrom()));
        mime.addHeader("X-Auto-Response-Suppress", "NDR, OOF, AutoReply");
        mime.addHeader("Precedence", "Special-Delivery, never-bounce");
        mime.setText(msg.makeSubstitutions(msg.getText()));
    } catch (MessagingException e) {
        log.error("iam mail build fails: " + e);
    }
    return mime;
}

From source file:com.jive.myco.seyren.core.service.notification.EmailNotificationService.java

private MimeMessage createMimeMessage(Email email) throws AddressException, MessagingException {

    MimeMessage mail = mailSender.createMimeMessage();
    InternetAddress senderAddress = new InternetAddress(email.getFrom());
    mail.addRecipient(RecipientType.TO, new InternetAddress(email.getTo()));
    mail.setSender(senderAddress);/*ww  w  . ja  va2 s  .  c  o m*/
    mail.setFrom(senderAddress);
    mail.setText(email.getMessage());
    mail.setSubject(email.getSubject());
    mail.addHeader("Content-Type", "text/html; charset=UTF-8");

    return mail;
}