Example usage for javax.mail Transport send

List of usage examples for javax.mail Transport send

Introduction

In this page you can find the example usage for javax.mail Transport send.

Prototype

public static void send(Message msg, Address[] addresses) throws MessagingException 

Source Link

Document

Send the message to the specified addresses, ignoring any recipients specified in the message itself.

Usage

From source file:org.apache.roller.planet.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type./*  ww  w  . ja va2s .  c  o m*/
 * 
 * @param from e-mail address of sender
 * @param to e-mail address(es) of recipients
 * @param subject subject of e-mail
 * @param content the body of the e-mail
 * @param mimeType type of message, i.e. text/plain or text/html
 * @throws MessagingException the exception to indicate failure
 */
public static void sendMessage(Session session, String from, String[] to, String[] cc, String[] bcc,
        String subject, String content, String mimeType) throws MessagingException {
    Message message = new MimeMessage(session);

    // n.b. any default from address is expected to be determined by caller.
    if (!StringUtils.isEmpty(from)) {
        InternetAddress sentFrom = new InternetAddress(from);
        message.setFrom(sentFrom);
        if (mLogger.isDebugEnabled())
            mLogger.debug("e-mail from: " + sentFrom);
    }

    if (to != null) {
        InternetAddress[] sendTo = new InternetAddress[to.length];

        for (int i = 0; i < to.length; i++) {
            sendTo[i] = new InternetAddress(to[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("sending e-mail to: " + to[i]);
        }
        message.setRecipients(Message.RecipientType.TO, sendTo);
    }

    if (cc != null) {
        InternetAddress[] copyTo = new InternetAddress[cc.length];

        for (int i = 0; i < cc.length; i++) {
            copyTo[i] = new InternetAddress(cc[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("copying e-mail to: " + cc[i]);
        }
        message.setRecipients(Message.RecipientType.CC, copyTo);
    }

    if (bcc != null) {
        InternetAddress[] copyTo = new InternetAddress[bcc.length];

        for (int i = 0; i < bcc.length; i++) {
            copyTo[i] = new InternetAddress(bcc[i]);
            if (mLogger.isDebugEnabled())
                mLogger.debug("blind copying e-mail to: " + bcc[i]);
        }
        message.setRecipients(Message.RecipientType.BCC, copyTo);
    }
    message.setSubject((subject == null) ? "(no subject)" : subject);
    message.setContent(content, mimeType);
    message.setSentDate(new java.util.Date());

    // First collect all the addresses together.
    Address[] remainingAddresses = message.getAllRecipients();
    int nAddresses = remainingAddresses.length;
    boolean bFailedToSome = false;

    SendFailedException sendex = new SendFailedException("Unable to send message to some recipients");

    // Try to send while there remain some potentially good addresses
    do {
        // Avoid a loop if we are stuck
        nAddresses = remainingAddresses.length;

        try {
            // Send to the list of remaining addresses, ignoring the addresses attached to the message
            Transport.send(message, remainingAddresses);
        } catch (SendFailedException ex) {
            bFailedToSome = true;
            sendex.setNextException(ex);

            // Extract the remaining potentially good addresses
            remainingAddresses = ex.getValidUnsentAddresses();
        }
    } while (remainingAddresses != null && remainingAddresses.length > 0
            && remainingAddresses.length != nAddresses);

    if (bFailedToSome)
        throw sendex;
}

From source file:com.hg.ecommerce.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type.//from  w w w.j  a  va 2  s . c  o  m
 *
 * @param from     e-mail address of sender
 * @param to       e-mail address(es) of recipients
 * @param subject  subject of e-mail
 * @param content  the body of the e-mail
 * @param mimeType type of message, i.e. text/plain or text/html
 * @throws MessagingException the exception to indicate failure
 */
public static void sendMessage(Session session, String from, String[] to, String[] cc, String[] bcc,
        String subject, String content, String mimeType) throws MessagingException {
    MimeMessage message = new MimeMessage(session);

    // n.b. any default from address is expected to be determined by caller.
    if (!StringUtils.isEmpty(from)) {
        InternetAddress sentFrom = new InternetAddress(from);
        message.setFrom(sentFrom);
        if (mLogger.isDebugEnabled()) {
            mLogger.debug("e-mail from: " + sentFrom);
        }
    }

    if (to != null) {
        InternetAddress[] sendTo = new InternetAddress[to.length];

        for (int i = 0; i < to.length; i++) {
            sendTo[i] = new InternetAddress(to[i]);
            if (mLogger.isDebugEnabled()) {
                mLogger.debug("sending e-mail to: " + to[i]);
            }
        }
        message.setRecipients(Message.RecipientType.TO, sendTo);
    }

    if (cc != null) {
        InternetAddress[] copyTo = new InternetAddress[cc.length];

        for (int i = 0; i < cc.length; i++) {
            copyTo[i] = new InternetAddress(cc[i]);
            if (mLogger.isDebugEnabled()) {
                mLogger.debug("copying e-mail to: " + cc[i]);
            }
        }
        message.setRecipients(Message.RecipientType.CC, copyTo);
    }

    if (bcc != null) {
        InternetAddress[] copyTo = new InternetAddress[bcc.length];

        for (int i = 0; i < bcc.length; i++) {
            copyTo[i] = new InternetAddress(bcc[i]);
            if (mLogger.isDebugEnabled()) {
                mLogger.debug("blind copying e-mail to: " + bcc[i]);
            }
        }
        message.setRecipients(Message.RecipientType.BCC, copyTo);
    }
    message.setSubject((subject == null) ? "(no subject)" : subject, "UTF-8");
    message.setContent(content, mimeType);
    message.setSentDate(new java.util.Date());

    // First collect all the addresses together.
    Address[] remainingAddresses = message.getAllRecipients();
    int nAddresses = remainingAddresses.length;
    boolean bFailedToSome = false;

    SendFailedException sendex = new SendFailedException("Unable to send message to some recipients");

    // Try to send while there remain some potentially good addresses
    do {
        // Avoid a loop if we are stuck
        nAddresses = remainingAddresses.length;

        try {
            // Send to the list of remaining addresses, ignoring the addresses attached to the message
            Transport.send(message, remainingAddresses);
        } catch (SendFailedException ex) {
            bFailedToSome = true;
            sendex.setNextException(ex);

            // Extract the remaining potentially good addresses
            remainingAddresses = ex.getValidUnsentAddresses();
        }
    } while (remainingAddresses != null && remainingAddresses.length > 0
            && remainingAddresses.length != nAddresses);

    if (bFailedToSome) {
        throw sendex;
    }
}

From source file:edu.harvard.iq.dataverse.MailServiceBean.java

public void sendMail(String host, String from, String to, String subject, String messageText) {
    Properties props = System.getProperties();
    props.put("mail.smtp.host", host);
    Session session = Session.getDefaultInstance(props, null);

    try {/*from  ww  w .j  ava 2 s  .  co  m*/
        MimeMessage msg = new MimeMessage(session);
        String[] recipientStrings = to.split(",");
        InternetAddress[] recipients = new InternetAddress[recipientStrings.length];
        try {
            msg.setFrom(new InternetAddress(from, charset));
            for (int i = 0; i < recipients.length; i++) {
                recipients[i] = new InternetAddress(recipientStrings[i], "", charset);
            }
        } catch (UnsupportedEncodingException ex) {
            logger.severe(ex.getMessage());
        }
        msg.setRecipients(Message.RecipientType.TO, recipients);
        msg.setSubject(subject, charset);
        msg.setText(messageText, charset);
        Transport.send(msg, recipients);
    } catch (AddressException ae) {
        ae.printStackTrace(System.out);
    } catch (MessagingException me) {
        me.printStackTrace(System.out);
    }
}

From source file:com.zxy.commons.email.MailMessageUtils.java

/**
 * inputStream??/*from  w  ww . jav  a 2  s  .  c  o  m*/
 * @param inputStream InputStream
 * @throws EmailException EmailException
 * @throws MessagingException MessagingException
*/
public static void sendEml(InputStream inputStream) throws EmailException, MessagingException {
    try {
        Session session = getEmail().getMailSession();
        MimeMessage message = new MimeMessage(session, inputStream);

        Transport.send(message, message.getAllRecipients());
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:org.rhq.enterprise.server.core.EmailManagerBean.java

/**
 * Send email to the addressses passed in toAddresses with the passed subject and body. Invalid emails will
 * be reported back. This can only catch sender errors up to the first smtp gateway.
 * @param  toAddresses list of email addresses to send to
 * @param  messageSubject subject of the email sent
 * @param  messageBody body of the email to be sent
 *
 * @return list of email receivers for which initial delivery failed.
 *///from   w  w w. j a  v  a  2s . c o  m
public Collection<String> sendEmail(Collection<String> toAddresses, String messageSubject, String messageBody) {

    MimeMessage mimeMessage = new MimeMessage(mailSession);
    try {
        mimeMessage.setSubject(messageSubject);
        mimeMessage.setContent(messageBody, "text/plain");
    } catch (MessagingException e) {
        e.printStackTrace(); // TODO: Customise this generated block
        return toAddresses;
    }

    Exception error = null;
    Collection<String> badAdresses = new ArrayList<String>(toAddresses.size());

    // Send to each recipient individually, do not throw exceptions until we try them all
    for (String toAddress : toAddresses) {
        try {
            LOG.debug("Sending email [" + messageSubject + "] to recipient [" + toAddress + "]");
            InternetAddress recipient = new InternetAddress(toAddress);
            Transport.send(mimeMessage, new InternetAddress[] { recipient });
        } catch (Exception e) {
            LOG.error("Failed to send email [" + messageSubject + "] to recipient [" + toAddress + "]: "
                    + e.getMessage());
            badAdresses.add(toAddress);

            // Remember the first error - in case its due to a session initialization problem,
            // we don't want to lose the first error.
            if (error == null) {
                error = e;
            }
        }
    }

    if (error != null) {
        LOG.error("Sending of emails failed for this reason: " + error.getMessage());
    }

    return badAdresses;
}

From source file:edu.harvard.iq.dataverse.MailServiceBean.java

public boolean sendSystemEmail(String to, String subject, String messageText) {

    boolean sent = false;
    String rootDataverseName = dataverseService.findRootDataverse().getName();
    String body = messageText + BundleUtil.getStringFromBundle("notification.email.closing",
            Arrays.asList(BrandingUtil.getInstallationBrandName(rootDataverseName)));
    logger.fine("Sending email to " + to + ". Subject: <<<" + subject + ">>>. Body: " + body);
    try {/*  ww  w  .j a  v a  2  s.  c o  m*/
        MimeMessage msg = new MimeMessage(session);
        InternetAddress systemAddress = getSystemAddress();
        if (systemAddress != null) {
            msg.setFrom(systemAddress);
            msg.setSentDate(new Date());
            String[] recipientStrings = to.split(",");
            InternetAddress[] recipients = new InternetAddress[recipientStrings.length];
            for (int i = 0; i < recipients.length; i++) {
                try {
                    recipients[i] = new InternetAddress('"' + recipientStrings[i] + '"', "", charset);
                } catch (UnsupportedEncodingException ex) {
                    logger.severe(ex.getMessage());
                }
            }
            msg.setRecipients(Message.RecipientType.TO, recipients);
            msg.setSubject(subject, charset);
            msg.setText(body, charset);
            try {
                Transport.send(msg, recipients);
                sent = true;
            } catch (SMTPSendFailedException ssfe) {
                logger.warning("Failed to send mail to " + to + " (SMTPSendFailedException)");
            }
        } else {
            logger.fine("Skipping sending mail to " + to + ", because the \"no-reply\" address not set ("
                    + Key.SystemEmail + " setting).");
        }
    } catch (AddressException ae) {
        logger.warning("Failed to send mail to " + to);
        ae.printStackTrace(System.out);
    } catch (MessagingException me) {
        logger.warning("Failed to send mail to " + to);
        me.printStackTrace(System.out);
    }
    return sent;
}

From source file:org.etudes.jforum.util.mail.Spammer.java

public boolean dispatchMessages() throws Exception {
    Address[] addresses = message.getAllRecipients();

    if (this.testMode) {
        Address addressFrom = null;/*w w  w  .j a  v a  2s.  co  m*/

        if (message.getFrom() != null && message.getFrom().length > 0) {
            addressFrom = message.getFrom()[0];
        }

        Address addressReplyTo[] = null;
        if (message.getReplyTo() != null) {
            addressReplyTo = message.getReplyTo();
        }
        testSendMail(addressFrom, addresses, message.getSubject(), message.getContent(), addressReplyTo);
        return true;
    }

    for (int i = 0; i < addresses.length; i++) {
        message.setRecipient(Message.RecipientType.TO, addresses[i]);
        Transport.send(message, new Address[] { addresses[i] });
    }

    /*if (SystemGlobals.getBoolValue(ConfigKeys.MAIL_SMTP_AUTH)) {
       if (username != null && !username.equals("") && password != null && !password.equals("")) {
    Transport transport = Spammer.getSession().getTransport("smtp");
            
    try {
       String host = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_HOST);
       if (host != null) {
          int colon = host.indexOf(':');
          if (colon > 0) {
             transport.connect(host.substring(0, colon), Integer.parseInt(host.substring(colon + 1)),
                   username, password);
          }
          else {
             transport.connect(host, username, password);
          }
       }
    }
    catch (MessagingException e) {
       throw new EmailException("Could not connect to the mail server", e);
    }
            
    if (transport.isConnected()) {
       Address[] addresses = message.getAllRecipients();
       for (int i = 0; i < addresses.length; i++) {
          // Tricks and tricks
          message.setRecipient(Message.RecipientType.TO, addresses[i]);
          transport.sendMessage(message, new Address[] { addresses[i] });
       }
    }
            
    transport.close();
       }
    }
    else {
       Address[] addresses = message.getAllRecipients();
       for (int i = 0; i < addresses.length; i++) {
    message.setRecipient(Message.RecipientType.TO, addresses[i]);
    Transport.send(message, new Address[] { addresses[i] });
       }
    }*/

    return true;
}

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

/**
 * Sends email with attachments/*from w  w  w .  ja v a  2s . 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);
        }
    }
}