Example usage for javax.mail.internet MimeMessage getAllRecipients

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

Introduction

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

Prototype

@Override
public Address[] getAllRecipients() throws MessagingException 

Source Link

Document

Get all the recipient addresses for the message.

Usage

From source file:com.ilopez.jasperemail.JasperEmail.java

public void emailReport(String emailHost, final String emailUser, final String emailPass,
        Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames,
        Boolean smtpauth, OptionValues.SMTPType smtpenc, Integer smtpport) throws MessagingException {

    Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, emailHost + " " + emailUser + " " + emailPass
            + " " + emailSender + " " + emailSubject + " " + smtpauth + " " + smtpenc + " " + smtpport);
    Properties props = new Properties();

    // Setup Email Settings
    props.setProperty("mail.smtp.host", emailHost);
    props.setProperty("mail.smtp.port", smtpport.toString());
    props.setProperty("mail.smtp.auth", smtpauth.toString());

    if (smtpenc == OptionValues.SMTPType.SSL) {
        // SSL settings
        props.put("mail.smtp.socketFactory.port", smtpport.toString());
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    } else if (smtpenc == OptionValues.SMTPType.TLS) {
        // TLS Settings
        props.put("mail.smtp.starttls.enable", "true");
    } else {//from   www .j  av  a2 s.  c o  m
        // Plain
    }

    // Setup and Apply the Email Authentication

    Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(emailUser, emailPass);
        }
    });

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject(emailSubject);
    for (String emailRecipient : emailRecipients) {
        Address toAddress = new InternetAddress(emailRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);
    }
    Address fromAddress = new InternetAddress(emailSender);
    message.setFrom(fromAddress);
    // Message text
    Multipart multipart = new MimeMultipart();
    BodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText("Database report attached\n\n");
    multipart.addBodyPart(textBodyPart);
    // Attachments
    for (String attachmentFileName : attachmentFileNames) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentFileName);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", "");
        fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", "");
        attachmentBodyPart.setFileName(fileNameWithoutPath);
        multipart.addBodyPart(attachmentBodyPart);
    }
    // add parts to message
    message.setContent(multipart);
    // send via SMTP
    Transport transport = mailSession.getTransport("smtp");

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

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(',');
        }//from  w  w  w.  j av  a  2 s  .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:com.gtwm.jasperexecute.RunJasperReports.java

public void emailReport(String emailHost, String emailUser, String emailPass, Set<String> emailRecipients,
        String emailSender, String emailSubject, List<String> attachmentFileNames) throws MessagingException {
    Properties props = new Properties();
    //props.setProperty("mail.debug", "true");
    props.setProperty("mail.smtp.host", emailHost);
    if (emailUser != null) {
        props.setProperty("mail.smtp.auth", "true");
    }//w w w  .j a v a2 s . c  o m
    Authenticator emailAuthenticator = new EmailAuthenticator(emailUser, emailPass);
    Session mailSession = Session.getDefaultInstance(props, emailAuthenticator);
    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject(emailSubject);
    for (String emailRecipient : emailRecipients) {
        Address toAddress = new InternetAddress(emailRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);
    }
    Address fromAddress = new InternetAddress(emailSender);
    message.setFrom(fromAddress);
    // Message text
    Multipart multipart = new MimeMultipart();
    BodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText("Database report attached\n\n");
    multipart.addBodyPart(textBodyPart);
    // Attachments
    for (String attachmentFileName : attachmentFileNames) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentFileName);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", "");
        fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", "");
        attachmentBodyPart.setFileName(fileNameWithoutPath);
        multipart.addBodyPart(attachmentBodyPart);
    }
    // add parts to message
    message.setContent(multipart);
    // send via SMTP
    Transport transport = mailSession.getTransport("smtp");
    // transport.connect(emailHost, emailUser, emailPass);
    transport.connect();
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}

From source file:org.protocoderrunner.apprunner.api.PNetwork.java

@ProtocoderScript
@APIMethod(description = "Send an E-mail. It requires passing a EmailConf object", example = "")
@APIParam(params = { "url", "function(data)" })
public void sendEmail(String from, String to, String subject, String text, final EmailConf emailSettings)
        throws AddressException, MessagingException {

    if (emailSettings == null) {
        return;/*from  www . jav a 2 s. com*/
    }

    // final String host = "smtp.gmail.com";
    // final String address = "@gmail.com";
    // final String pass = "";

    Multipart multiPart;
    String finalString = "";

    Properties props = System.getProperties();
    props.put("mail.smtp.starttls.enable", emailSettings.ttl);
    props.put("mail.smtp.host", emailSettings.host);
    props.put("mail.smtp.user", emailSettings.user);
    props.put("mail.smtp.password", emailSettings.password);
    props.put("mail.smtp.port", emailSettings.port);
    props.put("mail.smtp.auth", emailSettings.auth);

    Log.i("Check", "done pops");
    final Session session = Session.getDefaultInstance(props, null);
    DataHandler handler = new DataHandler(new ByteArrayDataSource(finalString.getBytes(), "text/plain"));
    final MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(from));
    message.setDataHandler(handler);
    Log.i("Check", "done sessions");

    multiPart = new MimeMultipart();

    InternetAddress toAddress;
    toAddress = new InternetAddress(to);
    message.addRecipient(Message.RecipientType.TO, toAddress);
    Log.i("Check", "added recipient");
    message.setSubject(subject);
    message.setContent(multiPart);
    message.setText(text);

    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            try {
                MLog.i("check", "transport");
                Transport transport = session.getTransport("smtp");
                MLog.i("check", "connecting");
                transport.connect(emailSettings.host, emailSettings.user, emailSettings.password);
                MLog.i("check", "wana send");
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();

                MLog.i("check", "sent");

            } catch (AddressException e) {
                e.printStackTrace();
            } catch (MessagingException e) {
                e.printStackTrace();
            }

        }
    });
    t.start();

}

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   w  w w  . j a va2s  .  co  m
        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:org.xwiki.commons.internal.DefaultMailSender.java

@Override
public int send(Mail mail) {
    Session session = null;//from w w w. j  a  v  a 2  s . c  o m
    Transport transport = null;
    if ((mail.getTo() == null || StringUtils.isEmpty(mail.getTo()))
            && (mail.getCc() == null || StringUtils.isEmpty(mail.getCc()))
            && (mail.getBcc() == null || StringUtils.isEmpty(mail.getBcc()))) {
        logger.error("This mail has no recipient");
        return 0;
    }
    if (mail.getContents().size() == 0) {
        logger.error("This mail is empty. You should add a content");
        return 0;
    }
    try {
        if ((transport == null) || (session == null)) {
            logger.info("Sending mail : Initializing properties");
            Properties props = initProperties();
            session = Session.getInstance(props, null);
            transport = session.getTransport("smtp");
            if (session.getProperty("mail.smtp.auth") == "true")
                transport.connect(session.getProperty("mail.smtp.server.username"),
                        session.getProperty("mail.smtp.server.password"));
            else
                transport.connect();
            try {
                Multipart wrapper = generateMimeMultipart(mail);
                InternetAddress[] adressesTo = this.toInternetAddresses(mail.getTo());
                MimeMessage message = new MimeMessage(session);
                message.setSentDate(new Date());
                message.setSubject(mail.getSubject());
                message.setFrom(new InternetAddress(mail.getFrom()));
                message.setRecipients(javax.mail.Message.RecipientType.TO, adressesTo);
                if (mail.getReplyTo() != null && !StringUtils.isEmpty(mail.getReplyTo())) {
                    logger.info("Adding ReplyTo field");
                    InternetAddress[] adressesReplyTo = this.toInternetAddresses(mail.getReplyTo());
                    if (adressesReplyTo.length != 0)
                        message.setReplyTo(adressesReplyTo);
                }
                if (mail.getCc() != null && !StringUtils.isEmpty(mail.getCc())) {
                    logger.info("Adding Cc recipients");
                    InternetAddress[] adressesCc = this.toInternetAddresses(mail.getCc());
                    if (adressesCc.length != 0)
                        message.setRecipients(javax.mail.Message.RecipientType.CC, adressesCc);
                }
                if (mail.getBcc() != null && !StringUtils.isEmpty(mail.getBcc())) {
                    InternetAddress[] adressesBcc = this.toInternetAddresses(mail.getBcc());
                    if (adressesBcc.length != 0)
                        message.setRecipients(javax.mail.Message.RecipientType.BCC, adressesBcc);
                }
                message.setContent(wrapper);
                message.setSentDate(new Date());
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
            } catch (SendFailedException sfex) {
                logger.error("Error encountered while trying to send the mail");
                logger.error("SendFailedException has occured.", sfex);
                try {
                    transport.close();
                } catch (MessagingException Mex) {
                    logger.error("MessagingException has occured.", Mex);
                }
                return 0;
            } catch (MessagingException mex) {
                logger.error("Error encountered while trying to send the mail");
                logger.error("MessagingException has occured.", mex);

                try {
                    transport.close();
                } catch (MessagingException ex) {
                    logger.error("MessagingException has occured.", ex);
                }
                return 0;
            }
        }
    } catch (Exception e) {
        System.out.println(e.toString());
        logger.error("Error encountered while trying to setup mail properties");
        try {
            if (transport != null) {
                transport.close();
            }
        } catch (MessagingException ex) {
            logger.error("MessagingException has occured.", ex);
        }
        return 0;
    }

    return 1;
}

From source file:com.midori.confluence.plugin.mail2news.Mail2NewsJob.java

/**
 * Send an mail containing the error message back to the
 * user which sent the given message./*  www .  ja va 2 s .c  o  m*/
 *
 * @param m The message which produced an error while handling it.
 * @param error The error string.
 */
private void sendErrorMessage(Message m, String error) throws Exception {
    /* get the SMTP mail server */
    SMTPMailServer smtpMailServer = MailFactory.getServerManager().getDefaultSMTPMailServer();
    if (smtpMailServer == null) {
        log.warn("Failed to send error message as no SMTP server is configured");
        return;
    }

    /* get system properties */
    Properties props = System.getProperties();

    /* Setup mail server */
    props.put("mail.smtp.host", smtpMailServer.getHostname());

    /* get a session */
    Session session = Session.getDefaultInstance(props, null);
    /* create the message */
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(smtpMailServer.getDefaultFrom()));
    String senderEmail = getEmailAddressFromMessage(m);
    if (senderEmail == "") {
        throw new Exception("Unknown sender of email.");
    }
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(senderEmail));
    message.setSubject("[mail2news] Error while handling message (" + m.getSubject() + ")");
    message.setText("An error occurred while handling your message:\n\n  " + error
            + "\n\nPlease contact the administrator to solve the problem.\n");

    /* send the message */
    Transport tr = session.getTransport("smtp");
    if (StringUtils.isBlank(smtpMailServer.getSmtpPort())) {
        tr.connect(smtpMailServer.getHostname(), smtpMailServer.getUsername(), smtpMailServer.getPassword());
    } else {
        int smtpPort = Integer.parseInt(smtpMailServer.getSmtpPort());
        tr.connect(smtpMailServer.getHostname(), smtpPort, smtpMailServer.getUsername(),
                smtpMailServer.getPassword());
    }
    message.saveChanges();
    tr.sendMessage(message, message.getAllRecipients());
    tr.close();
}

From source file:org.opens.emailsender.EmailSender.java

/**
 *
 * @param emailFrom/*from  w w  w.j a v a2  s . c o m*/
 * @param emailToSet
 * @param emailBccSet (can be null)
 * @param replyTo (can be null)
 * @param emailSubject
 * @param emailContent
 */
public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo,
        String emailSubject, String emailContent) {
    boolean debug = false;

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");

    // create some properties and get the default Session
    Session session = Session.getInstance(props);
    session.setDebug(debug);
    try {
        Transport t = session.getTransport("smtp");
        t.connect(smtpHost, userName, password);

        // create a message
        MimeMessage msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom;
        try {
            // Used default from address is passed one is null or empty or
            // blank
            addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom)
                    : new InternetAddress(from);
            msg.setFrom(addressFrom);
            Address[] recipients = new InternetAddress[emailToSet.size()];
            int i = 0;
            for (String emailTo : emailToSet) {
                recipients[i] = new InternetAddress(emailTo);
                i++;
            }

            msg.setRecipients(Message.RecipientType.TO, recipients);

            if (CollectionUtils.isNotEmpty(emailBccSet)) {
                Address[] bccRecipients = new InternetAddress[emailBccSet.size()];
                i = 0;
                for (String emailBcc : emailBccSet) {
                    bccRecipients[i] = new InternetAddress(emailBcc);
                    i++;
                }
                msg.setRecipients(Message.RecipientType.BCC, bccRecipients);
            }

            if (StringUtils.isNotBlank(replyTo)) {
                Address[] replyToRecipients = { new InternetAddress(replyTo) };
                msg.setReplyTo(replyToRecipients);
            }

            // Setting the Subject
            msg.setSubject(emailSubject, CHARSET_KEY);

            // Setting content and charset (warning: both declarations of
            // charset are needed)
            msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY);
            LOGGER.error("emailContent  " + emailContent);
            msg.setContent(emailContent, FULL_CHARSET_KEY);
            try {
                LOGGER.debug("emailContent from message object " + msg.getContent().toString());
            } catch (IOException ex) {
                LOGGER.error(ex.getMessage());
            } catch (MessagingException ex) {
                LOGGER.error(ex.getMessage());
            }
            for (Address addr : msg.getAllRecipients()) {
                LOGGER.error("addr " + addr);
            }
            t.sendMessage(msg, msg.getAllRecipients());
        } catch (AddressException ex) {
            LOGGER.warn(ex.getMessage());
        }
    } catch (NoSuchProviderException e) {
        LOGGER.warn(e.getMessage());
    } catch (MessagingException e) {
        LOGGER.warn(e.getMessage());
    }
}

From source file:org.asqatasun.emailsender.EmailSender.java

/**
 *
 * @param emailFrom/*from  w w w. ja  v  a2  s.  c om*/
 * @param emailToSet
 * @param emailBccSet (can be null)
 * @param replyTo (can be null)
 * @param emailSubject
 * @param emailContent
 */
public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo,
        String emailSubject, String emailContent) {
    boolean debug = false;

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");

    // create some properties and get the default Session
    Session session = Session.getInstance(props);
    session.setDebug(debug);
    try {
        Transport t = session.getTransport("smtp");
        t.connect(smtpHost, userName, password);

        // create a message
        MimeMessage msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom;
        try {
            // Used default from address is passed one is null or empty or
            // blank
            addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom)
                    : new InternetAddress(from);
            msg.setFrom(addressFrom);
            Address[] recipients = new InternetAddress[emailToSet.size()];
            int i = 0;
            for (String emailTo : emailToSet) {
                recipients[i] = new InternetAddress(emailTo);
                i++;
            }

            msg.setRecipients(Message.RecipientType.TO, recipients);

            if (CollectionUtils.isNotEmpty(emailBccSet)) {
                Address[] bccRecipients = new InternetAddress[emailBccSet.size()];
                i = 0;
                for (String emailBcc : emailBccSet) {
                    bccRecipients[i] = new InternetAddress(emailBcc);
                    i++;
                }
                msg.setRecipients(Message.RecipientType.BCC, bccRecipients);
            }

            if (StringUtils.isNotBlank(replyTo)) {
                Address[] replyToRecipients = { new InternetAddress(replyTo) };
                msg.setReplyTo(replyToRecipients);
            }

            // Setting the Subject
            msg.setSubject(emailSubject, CHARSET_KEY);

            // Setting content and charset (warning: both declarations of
            // charset are needed)
            msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY);
            LOGGER.debug("emailContent  " + emailContent);
            msg.setContent(emailContent, FULL_CHARSET_KEY);
            try {
                LOGGER.debug("emailContent from message object " + msg.getContent().toString());
            } catch (IOException ex) {
                LOGGER.error(ex.getMessage());
            } catch (MessagingException ex) {
                LOGGER.error(ex.getMessage());
            }
            for (Address addr : msg.getAllRecipients()) {
                LOGGER.debug("addr " + addr);
            }
            t.sendMessage(msg, msg.getAllRecipients());
        } catch (AddressException ex) {
            LOGGER.warn("AddressException " + ex.getMessage());
            LOGGER.warn("AddressException " + ex.getStackTrace());
        }
    } catch (NoSuchProviderException e) {
        LOGGER.warn("NoSuchProviderException " + e.getMessage());
        LOGGER.warn("NoSuchProviderException " + e.getStackTrace());
    } catch (MessagingException e) {
        LOGGER.warn("MessagingException " + e.getMessage());
        LOGGER.warn("MessagingException " + e.getStackTrace());
    }
}

From source file:edu.ku.brc.helpers.EMailHelper.java

/**
 * Send an email. Also sends it as a gmail if applicable, and does password checking.
 * @param host host of SMTP server/*from   w w w .j av a2  s .  c  o m*/
 * @param uName username of email account
 * @param pWord password of email account
 * @param fromEMailAddr the email address of who the email is coming from typically this is the same as the user's email
 * @param toEMailAddr the email addr of who this is going to
 * @param subject the Textual subject line of the email
 * @param bodyText the body text of the email (plain text???)
 * @param fileAttachment and optional file to be attached to the email
 * @return true if the msg was sent, false if not
 */
public static boolean sendMsgAsGMail(final String host, final String uName, final String pWord,
        final String fromEMailAddr, final String toEMailAddr, final String subject, final String bodyText,
        final String mimeType, @SuppressWarnings("unused") final String port,
        @SuppressWarnings("unused") final String security, final File fileAttachment) {
    String userName = uName;
    String password = pWord;
    Boolean fail = false;

    ArrayList<String> userAndPass = new ArrayList<String>();

    Properties props = System.getProperties();

    props.put("mail.smtp.host", host); //$NON-NLS-1$
    props.put("mail.smtp.auth", "true"); //$NON-NLS-1$ //$NON-NLS-2$
    props.put("mail.smtp.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$
    props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    boolean usingSSL = false;
    if (usingSSL) {
        props.put("mail.smtps.port", "587"); //$NON-NLS-1$ //$NON-NLS-2$
        props.put("mail.smtp.starttls.enable", "true"); //$NON-NLS-1$ //$NON-NLS-2$

    }

    Session session = Session.getInstance(props, null);

    session.setDebug(instance.isDebugging);
    if (instance.isDebugging) {
        log.debug("Host:     " + host); //$NON-NLS-1$
        log.debug("UserName: " + userName); //$NON-NLS-1$
        log.debug("Password: " + password); //$NON-NLS-1$
        log.debug("From:     " + fromEMailAddr); //$NON-NLS-1$
        log.debug("To:       " + toEMailAddr); //$NON-NLS-1$
        log.debug("Subject:  " + subject); //$NON-NLS-1$
    }

    try {
        // create a message
        MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(fromEMailAddr));
        if (toEMailAddr.indexOf(",") > -1) //$NON-NLS-1$
        {
            StringTokenizer st = new StringTokenizer(toEMailAddr, ","); //$NON-NLS-1$
            InternetAddress[] address = new InternetAddress[st.countTokens()];
            int i = 0;
            while (st.hasMoreTokens()) {
                String toStr = st.nextToken().trim();
                address[i++] = new InternetAddress(toStr);
            }
            msg.setRecipients(Message.RecipientType.TO, address);
        } else {
            InternetAddress[] address = { new InternetAddress(toEMailAddr) };
            msg.setRecipients(Message.RecipientType.TO, address);
        }
        msg.setSubject(subject);

        //msg.setContent( aBodyText , "text/html;charset=\"iso-8859-1\"");

        // create the second message part
        if (fileAttachment != null) {
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setContent(bodyText, mimeType);//"text/html;charset=\"iso-8859-1\"");
            //mbp1.setContent(bodyText, "text/html;charset=\"iso-8859-1\"");

            MimeBodyPart mbp2 = new MimeBodyPart();

            // attach the file to the message
            FileDataSource fds = new FileDataSource(fileAttachment);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());

            // create the Multipart and add its parts to it
            Multipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);

            // add the Multipart to the message
            msg.setContent(mp);

        } else {
            // add the Multipart to the message
            msg.setContent(bodyText, mimeType);
        }

        // set the Date: header
        msg.setSentDate(new Date());

        // send the message
        int cnt = 0;
        do {
            cnt++;
            SMTPTransport t = (SMTPTransport) session.getTransport("smtp"); //$NON-NLS-1$
            try {
                t.connect(host, userName, password);

                t.sendMessage(msg, msg.getAllRecipients());

                fail = false;
            } catch (MessagingException mex) {
                edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
                edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
                instance.lastErrorMsg = mex.toString();

                Exception ex = null;
                if ((ex = mex.getNextException()) != null) {
                    ex.printStackTrace();
                    instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
                }

                //wrong username or password, get new one
                if (mex.toString().equals("javax.mail.AuthenticationFailedException")) //$NON-NLS-1$
                {
                    fail = true;
                    userAndPass = askForUserAndPassword((Frame) UIRegistry.getTopWindow());

                    if (userAndPass == null) {//the user is done
                        return false;
                    }
                    // else
                    //try again
                    userName = userAndPass.get(0);
                    password = userAndPass.get(1);
                }
            } finally {

                log.debug("Response: " + t.getLastServerResponse()); //$NON-NLS-1$
                t.close();
            }
        } while (fail && cnt < 6);

    } catch (MessagingException mex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
        instance.lastErrorMsg = mex.toString();

        //mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
            instance.lastErrorMsg = instance.lastErrorMsg + ", " + ex.toString(); //$NON-NLS-1$
        }
        return false;

    } catch (Exception ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, ex);
        ex.printStackTrace();
    }

    if (fail) {
        return false;
    } //else
    return true;
}