Example usage for javax.mail.internet MimeMessage setSubject

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

Introduction

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

Prototype

public void setSubject(String subject, String charset) throws MessagingException 

Source Link

Document

Set the "Subject" header field.

Usage

From source file:org.apache.james.protocols.smtp.AbstractStartTlsSMTPServerTest.java

@Test
public void testStartTLSWithJavamail() throws Exception {
    InetSocketAddress address = new InetSocketAddress("127.0.0.1", TestUtils.getFreePort());

    ProtocolServer server = null;//from  w w  w  . ja v  a  2  s  .com
    try {
        TestMessageHook hook = new TestMessageHook();
        server = createServer(createProtocol(hook), address,
                Encryption.createStartTls(BogusSslContextFactory.getServerContext()));
        server.bind();

        Properties mailProps = new Properties();
        mailProps.put("mail.smtp.from", "test@localhost");
        mailProps.put("mail.smtp.host", address.getHostName());
        mailProps.put("mail.smtp.port", address.getPort());
        mailProps.put("mail.smtp.socketFactory.class", BogusSSLSocketFactory.class.getName());
        mailProps.put("mail.smtp.socketFactory.fallback", "false");
        mailProps.put("mail.smtp.starttls.enable", "true");

        Session mailSession = Session.getDefaultInstance(mailProps);

        MimeMessage message = new MimeMessage(mailSession);
        message.setFrom(new InternetAddress("test@localhost"));
        String[] emails = { "valid@localhost" };
        Address rcpts[] = new Address[emails.length];
        for (int i = 0; i < emails.length; i++) {
            rcpts[i] = new InternetAddress(emails[i].trim().toLowerCase());
        }
        message.setRecipients(Message.RecipientType.TO, rcpts);
        message.setSubject("Testmail", "UTF-8");
        message.setText("Test.....");

        SMTPTransport transport = (SMTPTransport) mailSession.getTransport("smtps");

        transport.connect(new Socket(address.getHostName(), address.getPort()));
        transport.sendMessage(message, rcpts);

        assertEquals(1, hook.getQueued().size());

    } finally {
        if (server != null) {
            server.unbind();
        }
    }

}

From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java

public String sendMail() {
    try {//from w ww  .ja  va 2 s.c o m
        Properties props = new Properties();

        // Server
        if (smtpServer == null || smtpServer.equals("")) {
            log.info("samigo.email.smtpServer is not set");
            smtpServer = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService");
            if (smtpServer == null || smtpServer.equals("")) {
                log.info("smtp@org.sakaiproject.email.api.EmailService is not set");
                log.error(
                        "Please set the value of samigo.email.smtpServer or smtp@org.sakaiproject.email.api.EmailService");
                return "error";
            }
        }
        props.setProperty("mail.smtp.host", smtpServer);

        // Port
        if (smtpPort == null || smtpPort.equals("")) {
            log.warn("samigo.email.smtpPort is not set. The default port 25 will be used.");
        } else {
            props.setProperty("mail.smtp.port", smtpPort);
        }

        props.put("mail.smtp.sendpartial", "true");

        Session session = Session.getInstance(props, null);
        session.setDebug(true);
        MimeMessage msg = new MimeMessage(session);

        InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName);
        msg.setFrom(fromIA);

        //msg.addHeaderLine("Subject: " + subject);
        msg.setSubject(subject, "UTF-8");
        String noReplyEmaillAddress = ServerConfigurationService.getString("setup.request",
                "no-reply@" + ServerConfigurationService.getServerName());
        msg.addHeaderLine("To: " + noReplyEmaillAddress);
        msg.setText(message, "UTF-8");
        msg.addHeaderLine("Content-Type: text/html");

        ArrayList<InternetAddress> toIAList = new ArrayList<InternetAddress>();
        String email = "";
        Iterator iter = toEmailAddressList.iterator();
        while (iter.hasNext()) {
            try {
                email = (String) iter.next();
                toIAList.add(new InternetAddress(email));
            } catch (AddressException ae) {
                log.error("invalid email address: " + email);
            }
        }

        InternetAddress[] toIA = new InternetAddress[toIAList.size()];
        int count = 0;
        Iterator iter2 = toIAList.iterator();
        while (iter2.hasNext()) {
            toIA[count++] = (InternetAddress) iter2.next();
        }

        try {
            Transport transport = session.getTransport("smtp");
            msg.saveChanges();
            transport.connect();

            try {
                transport.sendMessage(msg, toIA);
            } catch (SendFailedException e) {
                log.debug("SendFailedException: " + e);
                return "error";
            } catch (MessagingException e) {
                log.warn("1st MessagingException: " + e);
                return "error";
            }
            transport.close();
        } catch (MessagingException e) {
            log.warn("2nd MessagingException:" + e);
            return "error";
        }

    } catch (UnsupportedEncodingException ue) {
        log.warn("UnsupportedEncodingException:" + ue);
        ue.printStackTrace();

    } catch (MessagingException me) {
        log.warn("3rd MessagingException:" + me);
        return "error";
    }
    return "send";
}

From source file:com.evolveum.midpoint.notifications.impl.api.transports.MailTransport.java

@Override
public void send(Message mailMessage, String transportName, Task task, OperationResult parentResult) {

    OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
    result.addCollectionOfSerializablesAsParam("mailMessage recipient(s)", mailMessage.getTo());
    result.addParam("mailMessage subject", mailMessage.getSubject());

    SystemConfigurationType systemConfiguration = NotificationsUtil
            .getSystemConfiguration(cacheRepositoryService, new OperationResult("dummy"));
    if (systemConfiguration == null || systemConfiguration.getNotificationConfiguration() == null
            || systemConfiguration.getNotificationConfiguration().getMail() == null) {
        String msg = "No notifications are configured. Mail notification to " + mailMessage.getTo()
                + " will not be sent.";
        LOGGER.warn(msg);/*from   ww w  . ja  va  2 s  .c  om*/
        result.recordWarning(msg);
        return;
    }

    MailConfigurationType mailConfigurationType = systemConfiguration.getNotificationConfiguration().getMail();
    String redirectToFile = mailConfigurationType.getRedirectToFile();
    if (redirectToFile != null) {
        try {
            TransportUtil.appendToFile(redirectToFile, formatToFile(mailMessage));
            result.recordSuccess();
        } catch (IOException e) {
            LoggingUtils.logException(LOGGER, "Couldn't write to mail redirect file {}", e, redirectToFile);
            result.recordPartialError("Couldn't write to mail redirect file " + redirectToFile, e);
        }
        return;
    }

    if (mailConfigurationType.getServer().isEmpty()) {
        String msg = "Mail server(s) are not defined, mail notification to " + mailMessage.getTo()
                + " will not be sent.";
        LOGGER.warn(msg);
        result.recordWarning(msg);
        return;
    }

    long start = System.currentTimeMillis();

    String from = mailConfigurationType.getDefaultFrom() != null ? mailConfigurationType.getDefaultFrom()
            : "nobody@nowhere.org";

    for (MailServerConfigurationType mailServerConfigurationType : mailConfigurationType.getServer()) {

        OperationResult resultForServer = result.createSubresult(DOT_CLASS + "send.forServer");
        final String host = mailServerConfigurationType.getHost();
        resultForServer.addContext("server", host);
        resultForServer.addContext("port", mailServerConfigurationType.getPort());

        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        if (mailServerConfigurationType.getPort() != null) {
            properties.setProperty("mail.smtp.port", String.valueOf(mailServerConfigurationType.getPort()));
        }
        MailTransportSecurityType mailTransportSecurityType = mailServerConfigurationType
                .getTransportSecurity();

        boolean sslEnabled = false, starttlsEnable = false, starttlsRequired = false;
        switch (mailTransportSecurityType) {
        case STARTTLS_ENABLED:
            starttlsEnable = true;
            break;
        case STARTTLS_REQUIRED:
            starttlsEnable = true;
            starttlsRequired = true;
            break;
        case SSL:
            sslEnabled = true;
            break;
        }
        properties.put("mail.smtp.ssl.enable", "" + sslEnabled);
        properties.put("mail.smtp.starttls.enable", "" + starttlsEnable);
        properties.put("mail.smtp.starttls.required", "" + starttlsRequired);
        if (Boolean.TRUE.equals(mailConfigurationType.isDebug())) {
            properties.put("mail.debug", "true");
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Using mail properties: ");
            for (Object key : properties.keySet()) {
                if (key instanceof String && ((String) key).startsWith("mail.")) {
                    LOGGER.debug(" - " + key + " = " + properties.get(key));
                }
            }
        }

        task.recordState("Sending notification mail via " + host);

        Session session = Session.getInstance(properties);

        try {
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress(from));
            for (String recipient : mailMessage.getTo()) {
                mimeMessage.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(recipient));
            }
            mimeMessage.setSubject(mailMessage.getSubject(), "utf-8");
            String contentType = mailMessage.getContentType();
            if (StringUtils.isEmpty(contentType)) {
                contentType = "text/plain; charset=UTF-8";
            }
            mimeMessage.setContent(mailMessage.getBody(), contentType);
            javax.mail.Transport t = session.getTransport("smtp");
            if (StringUtils.isNotEmpty(mailServerConfigurationType.getUsername())) {
                ProtectedStringType passwordProtected = mailServerConfigurationType.getPassword();
                String password = null;
                if (passwordProtected != null) {
                    try {
                        password = protector.decryptString(passwordProtected);
                    } catch (EncryptionException e) {
                        String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host
                                + ", because the plaintext password value couldn't be obtained. Trying another mail server, if there is any.";
                        LoggingUtils.logException(LOGGER, msg, e);
                        resultForServer.recordFatalError(msg, e);
                        continue;
                    }
                }
                t.connect(mailServerConfigurationType.getUsername(), password);
            } else {
                t.connect();
            }
            t.sendMessage(mimeMessage, mimeMessage.getAllRecipients());
            LOGGER.info("Message sent successfully to " + mailMessage.getTo() + " via server " + host + ".");
            resultForServer.recordSuccess();
            result.recordSuccess();
            long duration = System.currentTimeMillis() - start;
            task.recordState(
                    "Notification mail sent successfully via " + host + ", in " + duration + " ms overall.");
            task.recordNotificationOperation(NAME, true, duration);
            return;
        } catch (MessagingException e) {
            String msg = "Couldn't send mail message to " + mailMessage.getTo() + " via " + host
                    + ", trying another mail server, if there is any";
            LoggingUtils.logException(LOGGER, msg, e);
            resultForServer.recordFatalError(msg, e);
            task.recordState("Error sending notification mail via " + host);
        }
    }
    LOGGER.warn(
            "No more mail servers to try, mail notification to " + mailMessage.getTo() + " will not be sent.");
    result.recordWarning("Mail notification to " + mailMessage.getTo() + " could not be sent.");
    task.recordNotificationOperation(NAME, false, System.currentTimeMillis() - start);
}

From source file:io.mapzone.arena.share.app.EMailSharelet.java

private void sendEmail(final String toText, final String subjectText, final String messageText,
        final boolean withAttachment, final ImagePngContent image) throws Exception {
    MimeMessage msg = new MimeMessage(mailSession());

    msg.addRecipients(RecipientType.TO, InternetAddress.parse(toText, false));
    // TODO we need the FROM from the current user
    msg.addFrom(InternetAddress.parse("support@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) );
    msg.setReplyTo(InternetAddress.parse("DO_NOT_REPLY_TO_THIS_EMAIL@mapzone.io")); //ArenaConfigMBean.SMTP_USER ) );

    msg.setSubject(subjectText, "utf-8");
    if (withAttachment) {
        // add mime multiparts
        Multipart multipart = new MimeMultipart();

        BodyPart part = new MimeBodyPart();
        part.setText(messageText);/*from   ww w . j  a  va 2  s . c  o  m*/
        multipart.addBodyPart(part);

        // Second part is attachment
        part = new MimeBodyPart();
        part.setDataHandler(new DataHandler(new URLDataSource(new URL(image.imgResource))));
        part.setFileName("preview.png");
        part.setHeader("Content-ID", "preview");
        multipart.addBodyPart(part);

        // // third part in HTML with embedded image
        // part = new MimeBodyPart();
        // part.setContent( "<img src='cid:preview'>", "text/html" );
        // multipart.addBodyPart( part );

        msg.setContent(multipart);
    } else {
        msg.setText(messageText, "utf-8");
    }
    msg.setSentDate(new Date());
    Transport.send(msg);
}

From source file:de.tuttas.servlets.MailSender.java

private void transmitMail(MailObject mo) throws MessagingException {

    // creates a new session with an authenticator
    Authenticator auth = new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(Config.getInstance().user, Config.getInstance().pass);
        }/*from  w  w  w .ja v  a  2s.  com*/
    };
    Session session = Session.getInstance(properties, auth);
    // creates a new e-mail message
    MimeMessage msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(mo.getFrom()));
    InternetAddress[] toAddresses = mo.getRecipient();
    msg.setRecipients(Message.RecipientType.TO, toAddresses);
    InternetAddress[] bccAdresses = mo.getBcc();
    InternetAddress[] ccAdresses = mo.getCC();

    if (bccAdresses[0] != null)
        msg.setRecipients(Message.RecipientType.BCC, bccAdresses);
    if (ccAdresses[0] != null)
        msg.setRecipients(Message.RecipientType.CC, ccAdresses);
    msg.setSubject(mo.getSubject(), "UTF-8");

    msg.setSentDate(new Date());
    msg.setContent(mo.getContent(), "text/plain; charset=UTF-8");
    // sends the e-mail
    // TODO Kommentar entfernen
    Transport.send(msg);
}

From source file:org.wf.dp.dniprorada.util.Mail.java

@Override
public void send() throws EmailException {

    try {/*  w  ww .j  a  v a 2s .co m*/
        log.info("init");
        MultiPartEmail oMultiPartEmail = new MultiPartEmail();
        oMultiPartEmail.setHostName(getHost());
        log.info("getHost()=" + getHost());
        oMultiPartEmail.addTo(getTo(), "receiver");
        log.info("getTo()=" + getTo());
        oMultiPartEmail.setFrom(getFrom(), getFrom());//"iGov"
        log.info("getFrom()=" + getFrom());
        oMultiPartEmail.setSubject(getHead());
        log.info("getHead()=" + getHead());

        oMultiPartEmail.setAuthentication(getAuthUser(), getAuthPassword());
        log.info("getAuthUser()=" + getAuthUser());
        log.info("getAuthPassword()=" + getAuthPassword());
        oMultiPartEmail.setSmtpPort(getPort());
        log.info("getPort()=" + getPort());
        oMultiPartEmail.setSSL(isSSL());
        log.info("isSSL()=" + isSSL());
        oMultiPartEmail.setTLS(isTLS());
        log.info("isTLS()=" + isTLS());

        oSession = oMultiPartEmail.getMailSession();
        MimeMessage oMimeMessage = new MimeMessage(oSession);

        //oMimeMessage.setFrom(new InternetAddress(getFrom(), "iGov", DEFAULT_ENCODING));
        oMimeMessage.setFrom(new InternetAddress(getFrom(), getFrom()));
        //oMimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(sTo, sToName, DEFAULT_ENCODING));
        oMimeMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(getTo(), "recipient", DEFAULT_ENCODING));

        oMimeMessage.setSubject(getHead(), DEFAULT_ENCODING);

        _Attach(getBody());

        oMimeMessage.setContent(oMultiparts);

        //            oMimeMessage.getRecipients(Message.RecipientType.CC);
        Transport.send(oMimeMessage);
        log.info("[send]:Transport.send!");
    } catch (Exception exc) {
        log.error("[send]", exc);
        throw new EmailException("Error happened when sending email", exc);
    }
}

From source file:org.sigmah.server.mail.MailSenderImpl.java

@Override
public void sendFile(Email email, String fileName, InputStream fileStream) throws EmailException {
    final String user = email.getAuthenticationUserName();
    final String password = email.getAuthenticationPassword();

    final Properties properties = new Properties();
    properties.setProperty(MAIL_TRANSPORT_PROTOCOL, TRANSPORT_PROTOCOL);
    properties.setProperty(MAIL_SMTP_HOST, email.getHostName());
    properties.setProperty(MAIL_SMTP_PORT, Integer.toString(email.getSmtpPort()));

    final StringBuilder toBuilder = new StringBuilder();
    for (final String to : email.getToAddresses()) {
        if (toBuilder.length() > 0) {
            toBuilder.append(',');
        }/*  w  ww  .  j a v a2s .  c om*/
        toBuilder.append(to);
    }

    final StringBuilder ccBuilder = new StringBuilder();
    if (email.getCcAddresses().length > 0) {
        for (final String cc : email.getCcAddresses()) {
            if (ccBuilder.length() > 0) {
                ccBuilder.append(',');
            }
            ccBuilder.append(cc);
        }
    }

    final Session session = javax.mail.Session.getInstance(properties);
    try {
        final DataSource attachment = new ByteArrayDataSource(fileStream,
                FileType.fromExtension(FileType.getExtension(fileName), FileType._DEFAULT).getContentType());

        final Transport transport = session.getTransport();

        if (password != null) {
            transport.connect(user, password);
        } else {
            transport.connect();
        }

        final MimeMessage message = new MimeMessage(session);

        // Configures the headers.
        message.setFrom(new InternetAddress(email.getFromAddress(), false));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toBuilder.toString(), false));
        if (email.getCcAddresses().length > 0) {
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccBuilder.toString(), false));
        }

        message.setSubject(email.getSubject(), email.getEncoding());

        // Html body part.
        final MimeMultipart textMultipart = new MimeMultipart("alternative");

        final MimeBodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(email.getContent(), "text/html; charset=\"" + email.getEncoding() + "\"");
        textMultipart.addBodyPart(htmlBodyPart);

        final MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(textMultipart);

        // Attachment body part.
        final MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.setDataHandler(new DataHandler(attachment));
        attachmentPart.setFileName(fileName);
        attachmentPart.setDescription(fileName);

        // Mail multipart content.
        final MimeMultipart contentMultipart = new MimeMultipart("related");
        contentMultipart.addBodyPart(textBodyPart);
        contentMultipart.addBodyPart(attachmentPart);

        message.setContent(contentMultipart);
        message.saveChanges();

        // Sends the mail.
        transport.sendMessage(message, message.getAllRecipients());

    } catch (UnsupportedEncodingException ex) {
        throw new EmailException(
                "An error occured while encoding the mail content to '" + email.getEncoding() + "'.", ex);

    } catch (IOException ex) {
        throw new EmailException("An error occured while reading the attachment of an email.", ex);

    } catch (MessagingException ex) {
        throw new EmailException("An error occured while sending an email.", ex);
    }
}

From source file:org.etudes.component.app.jforum.JForumEmailServiceImpl.java

/**
 * Sends email with attachments//from w ww .  j a  va 2 s. c o m
 * 
 * @param from
 *        The address this message is to be listed as coming from.
 * @param to
 *        The address(es) this message should be sent to.
 * @param subject
 *        The subject of this message.
 * @param content
 *        The body of the message.
 * @param headerToStr
 *        If specified, this is placed into the message header, but "to" is used for the recipients.
 * @param replyTo
 *        If specified, this is the reply to header address(es).
 * @param additionalHeaders
 *        Additional email headers to send (List of String). For example, content type or forwarded headers (may be null)        
 * @param messageAttachments
 *         Message attachments
 */
protected void sendMailWithAttachments(InternetAddress from, InternetAddress[] to, String subject,
        String content, InternetAddress[] headerTo, InternetAddress[] replyTo, List<String> additionalHeaders,
        List<EmailAttachment> emailAttachments) {
    if (testMode) {
        testSendMail(from, to, subject, content, headerTo, replyTo, additionalHeaders, emailAttachments);
        return;
    }

    if (smtp == null || smtp.trim().length() == 0) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMailWithAttachments: smtp not set");
        }
        return;
    }

    if (from == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: from is needed to send email");
        }
        return;
    }

    if (to == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: to is needed to send email");
        }
        return;
    }

    if (content == null) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: content is needed to send email");
        }
        return;
    }

    if (emailAttachments == null || emailAttachments.size() == 0) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: emailAttachments are needed to send email with attachments");
        }
        return;
    }

    try {
        if (session == null) {
            if (logger.isWarnEnabled()) {
                logger.warn("mail session is null");
            }
            return;

        }
        MimeMessage message = new MimeMessage(session);

        // default charset
        String charset = "UTF-8";

        message.setSentDate(new Date());
        message.setFrom(from);
        message.setSubject(subject, charset);

        MimeBodyPart messageBodyPart = new MimeBodyPart();

        // Content-Type: text/plain; text/html;
        String contentType = null, contentTypeValue = null;

        if (additionalHeaders != null) {
            for (String header : additionalHeaders) {
                if (header.toLowerCase().startsWith("content-type:")) {
                    contentType = header;

                    contentTypeValue = contentType.substring(
                            contentType.indexOf("content-type:") + "content-type:".length(),
                            contentType.length());
                    break;
                }
            }
        }

        // message
        String messagetype = "";
        if ((contentTypeValue != null) && (contentTypeValue.trim().equalsIgnoreCase("text/html"))) {
            messagetype = "text/html; charset=" + charset;
            messageBodyPart.setContent(content, messagetype);
        } else {

            messagetype = "text/plain; charset=" + charset;
            messageBodyPart.setContent(content, messagetype);
        }

        //messageBodyPart.setContent(content, "text/html; charset="+ charset);

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        String jforumAttachmentStoreDir = serverConfigurationService()
                .getString(JForumAttachmentService.ATTACHMENTS_STORE_DIR);
        if (jforumAttachmentStoreDir == null || jforumAttachmentStoreDir.trim().length() == 0) {
            if (logger.isWarnEnabled()) {
                logger.warn("JForum attachments directory (" + JForumAttachmentService.ATTACHMENTS_STORE_DIR
                        + ") property is not set in sakai.properties ");
            }
        } else {
            // attachments
            for (EmailAttachment emailAttachment : emailAttachments) {

                String filePath = jforumAttachmentStoreDir + "/" + emailAttachment.getPhysicalFileName();

                messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(filePath);
                try {
                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(emailAttachment.getRealFileName());

                    multipart.addBodyPart(messageBodyPart);
                } catch (MessagingException e) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Error while attaching attachments: " + e, e);
                    }
                }
            }
        }

        message.setContent(multipart);

        Transport.send(message, to);

    } catch (MessagingException e) {
        if (logger.isWarnEnabled()) {
            logger.warn("sendMail: Error in sending email: " + e, e);
        }
    }
}

From source file:net.fenyo.mail4hotspot.service.MailManager.java

public void sendMessage(Address from_addr, Address[] to_addr, Address[] cc_addr, String subject, String content)
        throws MessagingException {
    final MimeMessage msg = new MimeMessage(session);

    msg.setFrom(from_addr);//from  w w  w  .j  a v a  2s.  com
    msg.setRecipients(Message.RecipientType.TO, to_addr);
    if (cc_addr.length > 0)
        msg.setRecipients(Message.RecipientType.CC, cc_addr);
    msg.setSubject(subject, "UTF-8");
    msg.setContent(content, "text/plain");

    transport.sendMessage(msg, ArrayUtils.addAll(to_addr, cc_addr));
}

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  ww w  .j  a va2  s .  co m*/

    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);
}