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:com.netspective.commons.message.SendMail.java

public void send(ValueContext vc, Map bodyTemplateVars) throws IOException, AddressException,
        MessagingException, SendMailNoFromAddressException, SendMailNoRecipientsException {
    if (from == null)
        throw new SendMailNoFromAddressException("No FROM address provided.");

    if (to == null && cc == null && bcc == null)
        throw new SendMailNoRecipientsException("No TO, CC, or BCC addresses provided.");

    Properties props = System.getProperties();
    props.put("mail.smtp.host", host.getTextValue(vc));

    Session mailSession = Session.getDefaultInstance(props, null);

    MimeMessage message = new MimeMessage(mailSession);

    if (headers != null) {
        List headersList = headers.getHeaders();
        for (int i = 0; i < headersList.size(); i++) {
            Header header = (Header) headersList.get(i);
            message.setHeader(header.getName(), header.getValue().getTextValue(vc));
        }//from ww w  . j  a  va  2s.  com
    }

    message.setFrom(new InternetAddress(from.getTextValue(vc)));

    if (replyTo != null)
        message.setReplyTo(getAddresses(replyTo.getValue(vc)));

    if (to != null)
        message.setRecipients(Message.RecipientType.TO, getAddresses(to.getValue(vc)));

    if (cc != null)
        message.setRecipients(Message.RecipientType.CC, getAddresses(cc.getValue(vc)));

    if (bcc != null)
        message.setRecipients(Message.RecipientType.BCC, getAddresses(bcc.getValue(vc)));

    if (subject != null)
        message.setSubject(subject.getTextValue(vc));

    if (body != null) {
        StringWriter messageText = new StringWriter();
        body.process(messageText, vc, bodyTemplateVars);
        message.setText(messageText.toString());
    }

    Transport.send(message);
}

From source file:com.stratelia.silverpeas.notificationserver.channel.smtp.SMTPListener.java

/**
 * send email to destination using SMTP protocol and JavaMail 1.3 API (compliant with MIME
 * format)./*from   w  w w.ja  va2  s  . c om*/
 *
 * @param pFrom : from field that will appear in the email header.
 * @param personalName :
 * @see {@link InternetAddress}
 * @param pTo : the email target destination.
 * @param pSubject : the subject of the email.
 * @param pMessage : the message or payload of the email.
 */
private void sendEmail(String pFrom, String personalName, String pTo, String pSubject, String pMessage,
        boolean htmlFormat) throws NotificationServerException {
    // retrieves system properties and set up Delivery Status Notification
    // @see RFC1891
    Properties properties = System.getProperties();
    properties.put("mail.smtp.host", getMailServer());
    properties.put("mail.smtp.auth", String.valueOf(isAuthenticated()));
    javax.mail.Session session = javax.mail.Session.getInstance(properties, null);
    session.setDebug(isDebug()); // print on the console all SMTP messages.
    Transport transport = null;
    try {
        InternetAddress fromAddress = getAuthorizedEmailAddress(pFrom, personalName);
        InternetAddress replyToAddress = null;
        InternetAddress[] toAddress = null;
        // parsing destination address for compliance with RFC822
        try {
            toAddress = InternetAddress.parse(pTo, false);
            if (!AdminReference.getAdminService().getAdministratorEmail().equals(pFrom)
                    && (!fromAddress.getAddress().equals(pFrom) || isForceReplyToSenderField())) {
                replyToAddress = new InternetAddress(pFrom, false);
                if (StringUtil.isDefined(personalName)) {
                    replyToAddress.setPersonal(personalName, CharEncoding.UTF_8);
                }
            }
        } catch (AddressException e) {
            SilverTrace.warn("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE",
                    "From = " + pFrom + ", To = " + pTo);
        }
        MimeMessage email = new MimeMessage(session);
        email.setFrom(fromAddress);
        if (replyToAddress != null) {
            email.setReplyTo(new InternetAddress[] { replyToAddress });
        }
        email.setRecipients(javax.mail.Message.RecipientType.TO, toAddress);
        email.setHeader("Precedence", "list");
        email.setHeader("List-ID", fromAddress.getAddress());
        String subject = pSubject;
        if (subject == null) {
            subject = "";
        }
        String content = pMessage;
        if (content == null) {
            content = "";
        }
        email.setSubject(subject, CharEncoding.UTF_8);
        if (content.toLowerCase().contains("<html>") || htmlFormat) {
            email.setContent(content, "text/html; charset=\"UTF-8\"");
        } else {
            email.setText(content, CharEncoding.UTF_8);
        }
        email.setSentDate(new Date());

        // create a Transport connection (TCP)
        if (isSecure()) {
            transport = session.getTransport(SECURE_TRANSPORT);
        } else {
            transport = session.getTransport(SIMPLE_TRANSPORT);
        }
        if (isAuthenticated()) {
            SilverTrace.info("smtp", "SMTPListner.sendEmail()", "root.MSG_GEN_PARAM_VALUE",
                    "Host = " + getMailServer() + " Port=" + getPort() + " User=" + getLogin());
            transport.connect(getMailServer(), getPort(), getLogin(), getPassword());
        } else {
            transport.connect();
        }

        transport.sendMessage(email, toAddress);
    } catch (MessagingException e) {
        Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        Logger.getLogger(getClass().getSimpleName()).log(Level.SEVERE, e.getMessage(), e);
    } catch (Exception e) {
        throw new NotificationServerException("SMTPListner.sendEmail()", SilverpeasException.ERROR,
                "smtp.EX_CANT_SEND_SMTP_MESSAGE", e);
    } finally {
        if (transport != null) {
            try {
                transport.close();
            } catch (Exception e) {
                SilverTrace.error("smtp", "SMTPListner.sendEmail()", "root.EX_IGNORED", "ClosingTransport", e);
            }
        }
    }
}

From source file:immf.ImodeForwardMail.java

@Override
public void buildMimeMessage() throws EmailException {
    super.buildMimeMessage();
    MimeMessage msg = this.getMimeMessage();
    try {/*from  w w  w. ja  va2s.c  o  m*/
        msg.setHeader("X-Mailer", ServerMain.Version);

        if (!this.conf.isRewriteAddress()) {
            // ??imode????????
            msg.setHeader("Resent-From", this.conf.getSmtpMailAddress());
            if (!this.conf.getForwardTo().isEmpty()) {
                msg.setHeader("Resent-To", StringUtils.join(this.conf.getForwardTo(), ","));
            }
            if (!this.conf.getForwardCc().isEmpty()) {
                msg.setHeader("Resent-Cc", StringUtils.join(this.conf.getForwardCc(), ","));
            }
            if (!this.conf.getForwardBcc().isEmpty()) {
                msg.setHeader("Resent-Bcc", StringUtils.join(this.conf.getForwardBcc(), ","));
            }
            SimpleDateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z (z)", Locale.US);
            msg.setHeader("Resent-Date", df.format(new Date()));
            msg.setHeader("Date", df.format(this.imm.getTimeDate()));

            msg.removeHeader("To");
            msg.removeHeader("Cc");
            msg.removeHeader("Bcc");

            List<InternetAddress> tolist = new ArrayList<InternetAddress>();
            List<InternetAddress> cclist = new ArrayList<InternetAddress>();

            boolean useMyAddress = false;
            if (this.imm.getFolderId() != ImodeNetClient.FolderIdSent) {
                if (this.conf.isHideMyaddr()) {
                    if (this.imm.getToAddrList().size() == 0) {
                        useMyAddress = true;
                    }
                } else {
                    useMyAddress = true;
                }
            }
            if (useMyAddress) {
                switch (this.imm.getRecvType()) {
                case ImodeMail.RECV_TYPE_TO:
                    tolist.add(this.imm.getMyInternetAddress());
                    break;
                case ImodeMail.RECV_TYPE_CC:
                    cclist.add(this.imm.getMyInternetAddress());
                    break;
                case ImodeMail.RECV_TYPE_BCC:
                    break;
                }
            }
            tolist.addAll(this.imm.getToAddrList());
            cclist.addAll(this.imm.getCcAddrList());

            msg.setHeader("To", InternetAddress.toString(tolist.toArray(new InternetAddress[0])));

            if (this.imm.getCcAddrList().size() > 0) {
                msg.setHeader("Cc", InternetAddress.toString(cclist.toArray(new InternetAddress[0])));
            }

            msg.setFrom(this.imm.getFromAddr());
        }

        String subject = null;
        if (imm.getFolderId() == ImodeNetClient.FolderIdSent) {
            subject = conf.getSentSubjectAppendPrefix() + imm.getSubject() + conf.getSentSubjectAppendSuffix();
        } else {
            subject = conf.getSubjectAppendPrefix() + imm.getSubject() + conf.getSubjectAppendSuffix();
        }
        if (conf.isSubjectEmojiReplace()) {
            subject = EmojiUtil.replaceToLabel(subject);
        }

        if (ImodeForwardMail.goomojiSubjectCharConv != null) {
            String goomojiSubject = ImodeForwardMail.goomojiSubjectCharConv.convert(subject);
            msg.setHeader("X-Goomoji-Source", "docomo_ne_jp");
            msg.setHeader("X-Goomoji-Subject", Util.encodeGoomojiSubject(goomojiSubject));
        }

        subject = ImodeForwardMail.subjectCharConv.convert(subject);
        msg.setSubject(MimeUtility.encodeText(subject, this.charset, "B"));

        if (this.conf.getContentTransferEncoding() != null) {
            msg.setHeader("Content-Transfer-Encoding", this.conf.getContentTransferEncoding());
        }

    } catch (Exception e) {
        log.warn(e);
    }
}

From source file:eu.peppol.outbound.HttpPostTestIT.java

@Test
public void testPost() throws Exception {

    InputStream resourceAsStream = HttpPostTestIT.class.getClassLoader()
            .getResourceAsStream(PEPPOL_BIS_INVOICE_SBDH_XML);
    assertNotNull(resourceAsStream,//from ww w  .  j a  v  a2  s. c o  m
            "Unable to locate resource " + PEPPOL_BIS_INVOICE_SBDH_XML + " in class path");

    X509Certificate ourCertificate = keystoreManager.getOurCertificate();

    SMimeMessageFactory SMimeMessageFactory = new SMimeMessageFactory(keystoreManager.getOurPrivateKey(),
            ourCertificate);
    MimeMessage signedMimeMessage = SMimeMessageFactory.createSignedMimeMessage(resourceAsStream,
            new MimeType("application/xml"));

    signedMimeMessage.writeTo(System.out);

    CloseableHttpClient httpClient = createCloseableHttpClient();

    HttpPost httpPost = new HttpPost(OXALIS_AS2_URL);

    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    signedMimeMessage.writeTo(byteArrayOutputStream);

    X500Principal subjectX500Principal = ourCertificate.getSubjectX500Principal();
    CommonName commonNameOfSender = CommonName.valueOf(subjectX500Principal);
    PeppolAs2SystemIdentifier asFrom = PeppolAs2SystemIdentifier.valueOf(commonNameOfSender);

    httpPost.addHeader(As2Header.AS2_FROM.getHttpHeaderName(), asFrom.toString());
    httpPost.addHeader(As2Header.AS2_TO.getHttpHeaderName(),
            new PeppolAs2SystemIdentifier(PeppolAs2SystemIdentifier.AS2_SYSTEM_ID_PREFIX + "AS2-TEST")
                    .toString());
    httpPost.addHeader(As2Header.DISPOSITION_NOTIFICATION_OPTIONS.getHttpHeaderName(),
            As2DispositionNotificationOptions.getDefault().toString());
    httpPost.addHeader(As2Header.AS2_VERSION.getHttpHeaderName(), As2Header.VERSION);
    httpPost.addHeader(As2Header.SUBJECT.getHttpHeaderName(), "AS2 TEST MESSAGE");
    httpPost.addHeader(As2Header.MESSAGE_ID.getHttpHeaderName(), UUID.randomUUID().toString());
    httpPost.addHeader(As2Header.DATE.getHttpHeaderName(), As2DateUtil.format(new Date()));

    // Inserts the S/MIME message to be posted
    httpPost.setEntity(
            new ByteArrayEntity(byteArrayOutputStream.toByteArray(), ContentType.create("multipart/signed")));

    CloseableHttpResponse postResponse = null; // EXECUTE !!!!
    try {
        postResponse = httpClient.execute(httpPost);
    } catch (HttpHostConnectException e) {
        fail("The Oxalis server does not seem to be running at " + OXALIS_AS2_URL);
    }

    HttpEntity entity = postResponse.getEntity(); // Any results?
    Assert.assertEquals(postResponse.getStatusLine().getStatusCode(), 200);
    String contents = EntityUtils.toString(entity);

    assertNotNull(contents);
    if (log.isDebugEnabled()) {
        log.debug("Received: \n");
        Header[] allHeaders = postResponse.getAllHeaders();
        for (Header header : allHeaders) {
            log.debug("" + header.getName() + ": " + header.getValue());
        }
        log.debug("\n" + contents);
        log.debug("---------------------------");
    }

    try {

        MimeMessage mimeMessage = MimeMessageHelper.parseMultipart(contents);
        System.out.println("Received multipart MDN response decoded as type : " + mimeMessage.getContentType());

        // Make sure we set content type header for the multipart message (should be multipart/signed)
        String contentTypeFromHttpResponse = postResponse.getHeaders("Content-Type")[0].getValue(); // Oxalis always return only one
        mimeMessage.setHeader("Content-Type", contentTypeFromHttpResponse);
        Enumeration<String> headerlines = mimeMessage.getAllHeaderLines();
        while (headerlines.hasMoreElements()) {
            // Content-Type: multipart/signed;
            // protocol="application/pkcs7-signature";
            // micalg=sha-1;
            // boundary="----=_Part_3_520186210.1399207766925"
            System.out.println("HeaderLine : " + headerlines.nextElement());
        }

        MdnMimeMessageInspector mdnMimeMessageInspector = new MdnMimeMessageInspector(mimeMessage);
        String msg = mdnMimeMessageInspector.getPlainTextPartAsText();
        System.out.println(msg);

    } finally {
        postResponse.close();
    }
}

From source file:jp.co.acroquest.endosnipe.collector.notification.smtp.SMTPSender.java

/**
 * ??//from w w  w  . j  av a  2s  .  c o  m
 * 
 * @param config javelin.properties???
 * @param entry ??
 * @return ???
 * @throws MessagingException ??????
 */
protected MimeMessage createMailMessage(final DataCollectorConfig config, final AlarmEntry entry)
        throws MessagingException {
    // JavaMail???
    Properties props = System.getProperties();
    String smtpServer = this.config_.getSmtpServer();
    if (smtpServer == null || smtpServer.length() == 0) {
        LOGGER.log(LogMessageCodes.SMTP_SERVER_NOT_SPECIFIED);
        String detailMessageKey = "collector.notification.smtp.SMTPSender.SMTPNotSpecified";
        String messageDetail = CommunicatorMessages.getMessage(detailMessageKey);

        throw new MessagingException(messageDetail);
    }
    props.setProperty(SMTP_HOST_KEY, smtpServer);
    int smtpPort = config.getSmtpPort();
    props.setProperty(SMTP_PORT_KEY, String.valueOf(smtpPort));

    // ???????
    Session session = null;
    if (authenticator_ == null) {
        // ?????
        session = Session.getDefaultInstance(props);
    } else {
        // ???
        props.setProperty(SMTP_AUTH_KEY, "true");
        session = Session.getDefaultInstance(props, authenticator_);
    }

    // MIME??
    MimeMessage message = new MimeMessage(session);

    // ??
    // :
    Date date = new Date();
    String encoding = this.config_.getSmtpEncoding();
    message.setHeader("X-Mailer", X_MAILER);
    message.setHeader("Content-Type", "text/plain; charset=\"" + encoding + "\"");
    message.setSentDate(date);

    // :from
    String from = this.config_.getSmtpFrom();
    InternetAddress fromAddr = new InternetAddress(from);
    message.setFrom(fromAddr);

    // :to
    String[] recipients = this.config_.getSmtpTo().split(",");
    for (String toStr : recipients) {
        InternetAddress toAddr = new InternetAddress(toStr);
        message.addRecipient(Message.RecipientType.TO, toAddr);
    }

    // :body, subject
    String subject;
    String body;
    subject = createSubject(entry, date);
    try {
        body = createBody(entry, date);
    } catch (IOException ex) {
        LOGGER.log(LogMessageCodes.FAIL_READ_MAIL_TEMPLATE, "");
        body = createDefaultBody(entry, date);
    }

    message.setSubject(subject, encoding);
    message.setText(body, encoding);

    return message;
}

From source file:de.betterform.connector.smtp.SMTPSubmissionHandler.java

private void send(String uri, byte[] data, String encoding, String mediatype) throws Exception {
    URL url = new URL(uri);
    String recipient = url.getPath();

    String server = null;/*from   w  ww.j ava2  s  . c o m*/
    String port = null;
    String sender = null;
    String subject = null;
    String username = null;
    String password = null;

    StringTokenizer headers = new StringTokenizer(url.getQuery(), "&");

    while (headers.hasMoreTokens()) {
        String token = headers.nextToken();

        if (token.startsWith("server=")) {
            server = URLDecoder.decode(token.substring("server=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("port=")) {
            port = URLDecoder.decode(token.substring("port=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("sender=")) {
            sender = URLDecoder.decode(token.substring("sender=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("subject=")) {
            subject = URLDecoder.decode(token.substring("subject=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("username=")) {
            username = URLDecoder.decode(token.substring("username=".length()), "UTF-8");

            continue;
        }

        if (token.startsWith("password=")) {
            password = URLDecoder.decode(token.substring("password=".length()), "UTF-8");

            continue;
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("smtp server '" + server + "'");

        if (username != null) {
            LOGGER.debug("smtp-auth username '" + username + "'");
        }

        LOGGER.debug("mail sender '" + sender + "'");
        LOGGER.debug("subject line '" + subject + "'");
    }

    Properties properties = System.getProperties();
    properties.put("mail.debug", String.valueOf(LOGGER.isDebugEnabled()));
    properties.put("mail.smtp.from", sender);
    properties.put("mail.smtp.host", server);

    if (port != null) {
        properties.put("mail.smtp.port", port);
    }

    if (username != null) {
        properties.put("mail.smtp.auth", String.valueOf(true));
        properties.put("mail.smtp.user", username);
    }

    Session session = Session.getInstance(properties, new SMTPAuthenticator(username, password));

    MimeMessage message = null;
    if (mediatype.startsWith("multipart/")) {
        message = new MimeMessage(session, new ByteArrayInputStream(data));
    } else {
        message = new MimeMessage(session);
        if (mediatype.toLowerCase().indexOf("charset=") == -1) {
            mediatype += "; charset=\"" + encoding + "\"";
        }
        message.setText(new String(data, encoding), encoding);
        message.setHeader("Content-Type", mediatype);
    }

    message.setRecipient(RecipientType.TO, new InternetAddress(recipient));
    message.setSubject(subject);
    message.setSentDate(new Date());

    Transport.send(message);
}

From source file:za.co.jumpingbean.alfresco.repo.EmailDocumentsAction.java

@Override
protected void executeImpl(Action action, NodeRef nodeRef) {
    try {//from  www  .j  a v  a 2s . c  om
        MimeMessage mimeMessage = mailService.createMimeMessage();
        mimeMessage.setFrom(new InternetAddress((String) action.getParameterValue(PARAM_FROM)));
        if (action.getParameterValue(PARAM_BCC) != null) {
            mimeMessage.setRecipients(Message.RecipientType.BCC, (String) action.getParameterValue(PARAM_BCC));
        }
        mimeMessage.setRecipients(Message.RecipientType.TO, (String) action.getParameterValue(PARAM_TO));
        mimeMessage.setSubject((String) action.getParameterValue(PARAM_SUBJECT));
        mimeMessage.setHeader("Content-Transfer-Encoding", "text/html; charset=UTF-8");
        addAttachments(action, nodeRef, mimeMessage);
        mailService.send(mimeMessage);
        logger.info("success!");
    } catch (AddressException ex) {
        logger.error("There was an error processing the email address for the mail documents action");
        logger.error(ex);
    } catch (MessagingException ex) {
        logger.error("There was an error processing the email for the mail documents action");
        logger.error(ex);
    } catch (MailException ex) {
        logger.error("There was an error processing the action");
        logger.error(ex);
    }
}

From source file:com.cws.esolutions.core.utils.EmailUtils.java

/**
 * Processes and sends an email message as generated by the requesting
 * application. This method is utilized with a JNDI datasource.
 *
 * @param mailConfig - The {@link com.cws.esolutions.core.config.xml.MailConfig} to utilize
 * @param message - The email message//ww  w. j  a v  a 2  s.  c  om
 * @param isWeb - <code>true</code> if this came from a container, <code>false</code> otherwise
 * @throws MessagingException {@link javax.mail.MessagingException} if an exception occurs sending the message
 */
public static final synchronized void sendEmailMessage(final MailConfig mailConfig, final EmailMessage message,
        final boolean isWeb) throws MessagingException {
    final String methodName = EmailUtils.CNAME
            + "#sendEmailMessage(final MailConfig mailConfig, final EmailMessage message, final boolean isWeb) throws MessagingException";

    Session mailSession = null;

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", mailConfig);
        DEBUGGER.debug("Value: {}", message);
        DEBUGGER.debug("Value: {}", isWeb);
    }

    SMTPAuthenticator smtpAuth = null;

    if (DEBUG) {
        DEBUGGER.debug("MailConfig: {}", mailConfig);
    }

    try {
        if (isWeb) {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup(EmailUtils.INIT_DS_CONTEXT);

            if (DEBUG) {
                DEBUGGER.debug("InitialContext: {}", initContext);
                DEBUGGER.debug("Context: {}", envContext);
            }

            if (envContext != null) {
                mailSession = (Session) envContext.lookup(mailConfig.getDataSourceName());
            }
        } else {
            Properties mailProps = new Properties();

            try {
                mailProps.load(
                        EmailUtils.class.getClassLoader().getResourceAsStream(mailConfig.getPropertyFile()));
            } catch (NullPointerException npx) {
                try {
                    mailProps.load(new FileInputStream(mailConfig.getPropertyFile()));
                } catch (IOException iox) {
                    throw new MessagingException(iox.getMessage(), iox);
                }
            } catch (IOException iox) {
                throw new MessagingException(iox.getMessage(), iox);
            }

            if (DEBUG) {
                DEBUGGER.debug("Properties: {}", mailProps);
            }

            if (StringUtils.equals((String) mailProps.get("mail.smtp.auth"), "true")) {
                smtpAuth = new SMTPAuthenticator();
                mailSession = Session.getDefaultInstance(mailProps, smtpAuth);
            } else {
                mailSession = Session.getDefaultInstance(mailProps);
            }
        }

        if (DEBUG) {
            DEBUGGER.debug("Session: {}", mailSession);
        }

        if (mailSession == null) {
            throw new MessagingException("Unable to configure email services");
        }

        mailSession.setDebug(DEBUG);
        MimeMessage mailMessage = new MimeMessage(mailSession);

        // Our emailList parameter should contain the following
        // items (in this order):
        // 0. Recipients
        // 1. From Address
        // 2. Generated-From (if blank, a default value is used)
        // 3. The message subject
        // 4. The message content
        // 5. The message id (optional)
        // We're only checking to ensure that the 'from' and 'to'
        // values aren't null - the rest is really optional.. if
        // the calling application sends a blank email, we aren't
        // handing it here.
        if (message.getMessageTo().size() != 0) {
            for (String to : message.getMessageTo()) {
                if (DEBUG) {
                    DEBUGGER.debug(to);
                }

                mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }

            mailMessage.setFrom(new InternetAddress(message.getEmailAddr().get(0)));
            mailMessage.setSubject(message.getMessageSubject());
            mailMessage.setContent(message.getMessageBody(), "text/html");

            if (message.isAlert()) {
                mailMessage.setHeader("Importance", "High");
            }

            Transport mailTransport = mailSession.getTransport("smtp");

            if (DEBUG) {
                DEBUGGER.debug("Transport: {}", mailTransport);
            }

            mailTransport.connect();

            if (mailTransport.isConnected()) {
                Transport.send(mailMessage);
            }
        }
    } catch (MessagingException mex) {
        throw new MessagingException(mex.getMessage(), mex);
    } catch (NamingException nx) {
        throw new MessagingException(nx.getMessage(), nx);
    }
}

From source file:jenkins.plugins.mailer.tasks.MimeMessageBuilder.java

private void setJenkinsInstanceIdent(MimeMessage msg) throws MessagingException {
    if (Jenkins.getInstance() != null) {
        String encodedIdentity;//from  www.jav  a  2s .  c  o m
        try {
            RSAPublicKey publicKey = InstanceIdentity.get().getPublic();
            encodedIdentity = Base64.encode(publicKey.getEncoded());
        } catch (Throwable t) {
            // Ignore. Just don't add the identity header.
            logError("Failed to set Jenkins Identity header on email.", t);
            return;
        }
        msg.setHeader("X-Instance-Identity", encodedIdentity);
    }
}

From source file:com.reizes.shiva.net.mail.Mail.java

public void sendHtmlMail(String fromName, String from, String to, String cc, String bcc, String subject,
        String content) throws UnsupportedEncodingException, MessagingException {
    boolean parseStrict = false;
    MimeMessage message = new MimeMessage(getSessoin());
    InternetAddress address = InternetAddress.parse(from, parseStrict)[0];

    if (fromName != null) {
        address.setPersonal(fromName, charset);
    }/*from  w w  w . j a  v a  2 s.c om*/

    message.setFrom(address);

    message.setRecipients(Message.RecipientType.TO, parseAddresses(to));

    if (cc != null) {
        message.setRecipients(Message.RecipientType.CC, parseAddresses(cc));
    }
    if (bcc != null) {
        message.setRecipients(Message.RecipientType.BCC, parseAddresses(bcc));
    }

    message.setSubject(subject, charset);

    message.setHeader("X-Mailer", "sendMessage");
    message.setSentDate(new java.util.Date()); //   

    Multipart multipart = new MimeMultipart();
    MimeBodyPart bodypart = new MimeBodyPart();
    bodypart.setContent(content, "text/html; charset=" + charset);
    multipart.addBodyPart(bodypart);

    message.setContent(multipart);
    Transport.send(message);
}