Example usage for javax.mail.internet MimeMessage setHeader

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

Introduction

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

Prototype

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

Source Link

Document

Set the value for this header_name.

Usage

From source file:org.apache.james.transport.mailets.HeadersToHTTP.java

private void addHeader(Mail mail, boolean success, String errorMessage) {
    try {/*from  www. j  ava 2  s. co  m*/
        MimeMessage message = mail.getMessage();
        message.setHeader("X-headerToHTTP", (success ? "Succeeded" : "Failed"));
        if (!success && errorMessage != null && errorMessage.length() > 0) {
            message.setHeader("X-headerToHTTPFailure", errorMessage);
        }
        message.saveChanges();
    } catch (MessagingException e) {
        log(e.getMessage());
    }
}

From source file:org.apache.james.transport.mailets.SerialiseToHTTP.java

private void addHeader(Mail mail, boolean success, String errorMessage) {
    try {// ww w  .ja  v  a  2s. c o m
        MimeMessage message = mail.getMessage();
        message.setHeader("X-toHTTP", (success ? "Succeeded" : "Failed"));
        if (!success && errorMessage != null && errorMessage.length() > 0) {
            message.setHeader("X-toHTTPFailure", errorMessage);
        }
        message.saveChanges();
    } catch (MessagingException e) {
        log(e.getMessage());
    }
}

From source file:com.enjoyxstudy.selenium.autoexec.mail.MailSender.java

/**
 * @param runner//from www  .  jav a 2s .  com
 * @param resultDir
 * @throws MessagingException
 * @throws IOException
 */
public void send(MultiHTMLSuiteRunner runner, File resultDir) throws MessagingException, IOException {

    MimeMessage mimeMessage = new MimeMessage(session);

    mimeMessage.setHeader("Content-Transfer-Encoding", "7bit");

    // To
    mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(config.getTo()));

    // From
    mimeMessage.setFrom(new InternetAddress(config.getFrom()));

    HashMap<String, Object> context = new HashMap<String, Object>();
    context.put("result", runner.getResult() ? "passed" : "failed");
    context.put("passedCount", new Integer(runner.getPassedCount()));
    context.put("failedCount", new Integer(runner.getFailedCount()));
    context.put("totalCount", new Integer(runner.getHtmlSuiteList().size()));
    context.put("startTime", new Date(runner.getStartTime()));
    context.put("endTime", new Date(runner.getEndTime()));
    context.put("htmlSuites", runner.getHtmlSuiteList());

    // subject
    mimeMessage.setSubject(TemplateUtils.merge(config.getSubject(), context), config.getCharset());

    // multipart message
    MimeMultipart content = new MimeMultipart();

    MimeBodyPart body = new MimeBodyPart();
    body.setText(TemplateUtils.merge(config.getBody(), context), config.getCharset());
    content.addBodyPart(body);

    File resultArchive = createResultArchive(resultDir);

    MimeBodyPart attachmentFile = new MimeBodyPart();
    attachmentFile.setDataHandler(new DataHandler(new FileDataSource(resultArchive)));
    attachmentFile.setFileName(RESULT_ARCHIVE_FILE);
    content.addBodyPart(attachmentFile);

    mimeMessage.setContent(content);

    // send mail
    _send(mimeMessage);
}

From source file:com.aurel.track.util.emailHandling.MailBuilder.java

private MimeMessage prepareHTMLMimeMessage(InternetAddress internetAddressFrom, String subject, String htmlBody,
        List<LabelValueBean> attachments) throws Exception {
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(internetAddressFrom);/*  w w  w.  j a  va 2  s.co m*/
    msg.setHeader(XMAILER, xmailer);
    msg.setSubject(subject.trim(), mailEncoding);
    msg.setSentDate(new Date());

    MimeMultipart mimeMultipart = new MimeMultipart("related");

    BodyPart messageBodyPart = new MimeBodyPart();
    //Euro sign finally, shown correctly
    messageBodyPart.setContent(htmlBody, "text/html;charset=" + mailEncoding);
    mimeMultipart.addBodyPart(messageBodyPart);

    if (attachments != null && !attachments.isEmpty()) {
        LOGGER.debug("Use attachments: " + attachments.size());
        includeAttachments(mimeMultipart, attachments);
    }

    msg.setContent(mimeMultipart);

    return msg;
}

From source file:com.aurel.track.util.emailHandling.MailBuilder.java

/**
 * Prepares a plain MimeMessage: the MimeMessage.RecipientType.TO is not yet set
 * @return/* w ww. j a v  a  2s .c  o  m*/
 * @throws Exception
 */
private MimeMessage preparePlainMimeMessage(InternetAddress internetAddressFrom, String subject,
        String plainBody, List<LabelValueBean> attachments) throws Exception {
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(internetAddressFrom);
    msg.setHeader(XMAILER, xmailer);
    msg.setSubject(subject.trim(), mailEncoding);
    msg.setSentDate(new Date());
    if (attachments == null || attachments.isEmpty()) {
        msg.setText(plainBody, mailEncoding);
    } else {
        MimeMultipart mimeMultipart = new MimeMultipart();

        MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setText(plainBody, mailEncoding);
        mimeMultipart.addBodyPart(textBodyPart);

        if (attachments != null) {
            includeAttachments(mimeMultipart, attachments);
        }

        msg.setContent(mimeMultipart);
    }
    return msg;
}

From source file:net.duckling.ddl.service.mail.impl.MailServiceImpl.java

private void cheat(MimeMessage mimeMessage, String serverDomain) throws MessagingException {
    mimeMessage.saveChanges();/*from ww  w . ja  v a2 s.  c o  m*/
    mimeMessage.setHeader("User-Agent", "Thunderbird 2.0.0.16 (Windows/20080708)");
    String messageid = mimeMessage.getHeader("Message-ID", null);
    messageid = messageid.replaceAll("\\.JavaMail.*", "@" + serverDomain + ">");
    mimeMessage.setHeader("Message-ID", messageid);
}

From source file:com.zimbra.cs.service.admin.VerifyStoreManager.java

private ParsedMessage getMessage(int size) throws Exception {
    MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession());
    mm.setHeader("From", " Jimmy <jimmy@example.com>");
    mm.setHeader("To", " Janis <janis@example.com>");
    mm.setHeader("Subject", "Hello");
    mm.setHeader("Message-ID", "<sakfuslkdhflskjch@oiwm.example.com>");
    mm.setText("nothing to see here\r\n" + RandomStringUtils.random(size));
    return new ParsedMessage(mm, false);
}

From source file:com.buzzdavidson.spork.util.OWAUtils.java

public static void populateMetadata(MimeMessage message, Node props) {
    Long length = null;/* w  ww  .j ava  2s  .c o m*/
    String lengthStr = fetchText(props, OWAConstants.OWA_FILTER_CONTENT_LENGTH, false);
    if (lengthStr != null) {
        try {
            length = Long.parseLong(lengthStr);
            logger.info("Got content length: " + length);
        } catch (NumberFormatException ex) {
            // do nothing
        }
    }
    //This appears to be the exchange specific message id,
    //looks like      "AQUAAAABXRM/AQAAAAA6N1oAAAAA"
    String idStr = fetchText(props, OWAConstants.OWA_FILTER_ID, false);
    if (idStr != null) {
        try {
            String headerId = "";
            String[] ids = message.getHeader("Message-Id");
            if (ids.length > 0) {
                headerId = ids[0];
            }
            if (headerId.length() > 0) {
                if (!headerId.equals(idStr)) {
                    logger.warn(String.format("******** ID values differ!  header id [%s], message id [%s]",
                            headerId, idStr));
                }
            } else {
                message.setHeader("Message-Id", idStr);
            }
        } catch (MessagingException ex) {
            logger.warn("Unable to handle message id header");
        }
    }
    //TODO: attachment flag? Is this needed at all? owabridge uses it to tweak content-length
    if (length != null) {
        try {
            message.setHeader("Content-Length", length.toString());
        } catch (MessagingException ex) {
            logger.warn("Unable to set content-length header", ex);
        }
    }
}

From source file:jease.cms.service.Mails.java

/**
 * Sends an email synchronously.//from  w w  w  .  j  a v  a 2  s.  co  m
 */
public void send(String sender, String recipients, String subject, String text) throws MessagingException {
    if (properties != null) {
        Session session = Session.getInstance(properties.asProperties(), new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(properties.getUser(), properties.getPassword());
            }
        });
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(sender));
        message.setReplyTo(new InternetAddress[] { new InternetAddress(sender) });
        message.setRecipients(Message.RecipientType.TO, recipients);
        message.setSubject(subject, "utf-8");
        message.setSentDate(new Date());
        message.setHeader("Content-Type", "text/plain; charset=\"utf-8\"");
        message.setHeader("Content-Transfer-Encoding", "quoted-printable");
        message.setText(text, "utf-8");
        Transport.send(message);
    }
}

From source file:com.emc.plants.service.impl.MailerBean.java

/** 
 * Create a mail message and send it./*  w w w. j a v  a  2s.com*/
 *
 * @param customerInfo  Customer information.
 * @param orderKey
 * @throws MailerAppException
 */
public void createAndSendMail(CustomerInfo customerInfo, long orderKey) throws MailerAppException {
    try {
        EMailMessage eMessage = new EMailMessage(createSubjectLine(orderKey), createMessage(orderKey),
                customerInfo.getCustomerID());
        Util.debug("Sending message" + "\nTo: " + eMessage.getEmailReceiver() + "\nSubject: "
                + eMessage.getSubject() + "\nContents: " + eMessage.getHtmlContents());

        //Session mailSession = (Session) Util.getInitialContext().lookup(MAIL_SESSION);

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(eMessage.getEmailReceiver(), false));

        msg.setSubject(eMessage.getSubject());
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setText(eMessage.getHtmlContents(), "us-ascii");
        msg.setHeader("X-Mailer", "JavaMailer");
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp);
        msg.setContent(mp);
        msg.setSentDate(new Date());

        Transport.send(msg);

        Util.debug("\nMail sent successfully.");
    } catch (Exception e) {
        Util.debug("Error sending mail. Have mail resources been configured correctly?");
        Util.debug("createAndSendMail exception : " + e);
        e.printStackTrace();
        throw new MailerAppException("Failure while sending mail");
    }
}