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:org.apache.jsieve.mailet.FileIntoAction.java

private static MimeMessage createMimeMessage(Mail aMail, MailAddress recipient) throws MessagingException {
    // Adapted from LocalDelivery Mailet
    // Add qmail's de facto standard Delivered-To header
    MimeMessage localMessage = new MimeMessage(aMail.getMessage()) {
        protected void updateHeaders() throws MessagingException {
            if (getMessageID() == null)
                super.updateHeaders();
            else//from   www.  j a va2s. co  m
                modified = false;
        }
    };
    localMessage.addHeader("Delivered-To", recipient.toString());

    localMessage.saveChanges();
    return localMessage;
}

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

private static void populateReceived(Node mailNode, MimeMessage message) throws MessagingException {
    String data = fetchText(mailNode, PATTERN_MAP.get("received"), false);
    if (data != null && data.length() > 0) {
        for (String line : splitReceived(data)) {
            message.addHeader(HEADER_MAP.get("received"), line);
        }//from  www  .  ja v  a  2s.c  o  m
    }
}

From source file:com.zimbra.cs.mailbox.MailboxTestUtil.java

public static ParsedMessage generateHighPriorityMessage(String subject) throws Exception {
    MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession());
    mm.setHeader("From", "Hi Bob <bob@example.com>");
    mm.setHeader("To", "Jimmy Dean <jdean@example.com>");
    mm.setHeader("Subject", subject);
    mm.addHeader("Importance", "high");
    mm.setText("nothing to see here");
    return new ParsedMessage(mm, false);
}

From source file:com.zimbra.cs.mailbox.MailboxTestUtil.java

public static ParsedMessage generateLowPriorityMessage(String subject) throws Exception {
    MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession());
    mm.setHeader("From", "Lo Bob <bob@example.com>");
    mm.setHeader("To", "Jimmy Dean <jdean@example.com>");
    mm.setHeader("Subject", subject);
    mm.addHeader("Importance", "low");
    mm.setText("nothing to see here");
    return new ParsedMessage(mm, false);
}

From source file:gmailclientfx.core.GmailClient.java

public static void sendMessage(String to, String subject, String body, List<String> attachments)
        throws Exception {
    // authenticate with gmail smtp server
    SMTPTransport smtpTransport = connectToSmtp("smtp.gmail.com", 587, EMAIL, ACCESS_TOKEN, true);

    // kreiraj MimeMessage objekt
    MimeMessage msg = new MimeMessage(OAuth2Authenticator.getSession());

    // dodaj headere
    msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
    msg.addHeader("format", "flowed");
    msg.addHeader("Content-Transfer-Encoding", "8bit");

    msg.setFrom(new InternetAddress(EMAIL));
    msg.setRecipients(javax.mail.Message.RecipientType.CC, InternetAddress.parse(to));
    msg.setSubject(subject, "UTF-8");
    msg.setReplyTo(InternetAddress.parse(EMAIL, false));

    // tijelo poruke
    BodyPart msgBodyPart = new MimeBodyPart();
    msgBodyPart.setText(body);//from   ww  w.  ja  v  a 2 s. c o m

    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(msgBodyPart);
    msg.setContent(multipart);

    // dodaj privitke
    if (attachments.size() > 0) {
        for (String attachment : attachments) {
            msgBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(attachment);
            msgBodyPart.setDataHandler(new DataHandler(source));
            msgBodyPart.setFileName(source.getName());
            multipart.addBodyPart(msgBodyPart);
        }
        msg.setContent(multipart);
    }
    smtpTransport.sendMessage(msg, InternetAddress.parse(to));

    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setTitle("Poruka poslana!");
    alert.setHeaderText(null);
    alert.setContentText("Email uspjeno poslan!");
    alert.showAndWait();
}

From source file:org.pentaho.reporting.engine.classic.extensions.modules.mailer.MailProcessor.java

public static void performBursting(final MailDefinition definition, final Session session)
        throws MessagingException, ReportProcessingException, ContentIOException {
    if (session == null) {
        throw new NullPointerException();
    }//from ww w  .  j  av a 2s  .  c  o  m

    // process parameters - validate!
    final ReportParameterValues parameterValues = definition.getParameterValues();
    final DefaultParameterContext parameterContext = new DefaultParameterContext(definition.getDataFactory(),
            parameterValues, ClassicEngineBoot.getInstance().getGlobalConfig(),
            definition.getResourceBundleFactory(), definition.getResourceManager(), definition.getContextKey(),
            definition.getReportEnvironment());

    try {
        final ReportParameterDefinition parameterDefinition = definition.getParameterDefinition();
        final ReportParameterValidator reportParameterValidator = parameterDefinition.getValidator();
        final ValidationResult validationResult = reportParameterValidator.validate(new ValidationResult(),
                parameterDefinition, parameterContext);
        if (validationResult.isEmpty() == false) {
            throw new ReportParameterValidationException(
                    "The parameters provided for this report are not valid.", validationResult);
        }
    } finally {
        parameterContext.close();
    }

    // definition: Single mail or multi-mail
    final TableModel burstingData;
    final DataFactory dataFactory = definition.getDataFactory();
    if (definition.getBurstQuery() != null
            && dataFactory.isQueryExecutable(definition.getBurstQuery(), parameterValues)) {
        burstingData = wrapWithParameters(dataFactory.queryData(definition.getBurstQuery(), parameterValues),
                parameterValues);
    } else {
        burstingData = wrapWithParameters(new DefaultTableModel(1, 0), parameterValues);
    }

    if (burstingData.getRowCount() > 0) {
        // final Transport transport = session.getTransport();
        // transport.connect();
        for (int i = 0; i < burstingData.getRowCount(); i++) {
            final DataRow parameterDataRow = createReportParameterDataRow(burstingData, i);
            final MimeMessage message = createReport(definition, session, parameterDataRow);

            parameterContext.setParameterValues(parameterDataRow);

            final MailHeader[] headers = definition.getHeaders();
            for (int j = 0; j < headers.length; j++) {
                final MailHeader header = headers[j];
                message.addHeader(header.getName(), header.getValue(parameterContext));
            }

            processRecipients(definition, message, dataFactory, parameterDataRow);

            // transport.sendMessage(message, message.getAllRecipients());
        }
        // transport.close();
    }
}

From source file:org.apache.niolex.commons.mail.EmailUtil.java

/**
 * Send an email./*from  w  ww  .ja v  a2s .co m*/
 * ????
 *
 * @param from the email sender
 * @param tos the email receivers array
 * @param ccs the carbon copiers array
 * @param title the email title
 * @param text the email body
 * @param attachments the email attachments list
 * @param priority priority from 1-5 the smaller is higher
 * @param isHtml is the text in HTML format or not
 * @param encoding the encoding of email, i.e. "GBK"?"UTF-8"
 * @throws MailException
 * @throws MessagingException
 */
public static void sendMail(String from, String[] tos, String[] ccs, String title, String text,
        List<Pair<String, InputStreamSource>> attachments, String priority, boolean isHtml, String encoding)
        throws MailException, MessagingException {
    MimeMessage mimeMessage = mailSender.createMimeMessage();
    MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, encoding);

    messageHelper.setFrom(from);
    messageHelper.setBcc(from);

    if (ArrayUtils.isEmpty(tos)) {
        throw new IllegalArgumentException("<tos> can not be null or empty!");
    } else {
        messageHelper.setTo(tos);
    }

    if (!ArrayUtils.isEmpty(ccs)) {
        messageHelper.setCc(ccs);
    }

    messageHelper.setSubject(title);
    messageHelper.setText(text, isHtml);

    if (attachments != null) {
        for (Pair<String, InputStreamSource> pair : attachments) {
            messageHelper.addAttachment(pair.a, pair.b);
        }
    }

    mimeMessage = messageHelper.getMimeMessage();
    if (priority != null) {
        mimeMessage.addHeader("X-Priority", priority);
    }

    mailSender.send(mimeMessage);
}

From source file:org.apache.james.postage.mail.AbstractMailFactory.java

/**
 * generates a mail containing data common to all test mails: postage headers, 
 *//*from w  w w.j  av a 2 s  .  co  m*/
public Message createMail(Session mailSession, MailSender mailSender,
        MailProcessingRecord mailProcessingRecord) {

    MimeMessage message = new MimeMessage(mailSession);

    try {
        message.addHeader(HeaderConstants.JAMES_POSTAGE_HEADER, "This is a test mail sent by James Postage");
        message.addHeader(HeaderConstants.JAMES_POSTAGE_VALIDATORCLASSNAME_HEADER,
                getValidatorClass().getName());
        message.setSubject(mailSender.getSubject());
        message.addHeader("Message-ID", "Postage-" + System.currentTimeMillis());
        mailProcessingRecord.setSubject(mailSender.getSubject());

        if (mailProcessingRecord.getMailId() != null) {
            message.addHeader(HeaderConstants.MAIL_ID_HEADER, mailProcessingRecord.getMailId());
        } else {
            log.warn("ID header is NULL!");
            throw new RuntimeException("could not create mail with ID = NULL");
        }

        populateMessage(message, mailSender, mailProcessingRecord);

    } catch (MessagingException e) {
        mailProcessingRecord.setErrorTextSending(e.toString());
        log.error("mail could not be created", e);
        return null;
    }
    return message;
}

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

public void prepare(MimeMessage message) throws Exception {

    message.addHeader("List-Unsubscribe", "<" + getUnsubscribeUrlOrEmail() + ">");

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

    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 (getBcc() != null) {
        message.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(getBcc()));
    }
    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.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");
        textBodyPart.setHeader("Content-Transfer-Encoding", "base64");
        textBodyPart.setContent(getPlainTextContent(), "text/plain; charset=\"UTF-8\"");
        mimeMultipart.addBodyPart(textBodyPart);
    }

    if (getHtmlContent() != null) {
        BodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setHeader("Content-Type", "text/html; charset=\"UTF-8\"");
        htmlBodyPart.setHeader("Content-Transfer-Encoding", "base64");
        htmlBodyPart.setContent(getHtmlContent(), "text/html; charset=\"UTF-8\"");
        mimeMultipart.addBodyPart(htmlBodyPart);
    }

}

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

private void putDeliveryHeadersBack(MimeMessage message, List<String> deliveredToHeader)
        throws MessagingException {
    for (String deliveredTo : deliveredToHeader) {
        message.addHeader(DELIVERED_TO, deliveredTo);
    }//  w w  w .j a  v  a  2s  .co m
}