Example usage for javax.mail.internet MimeMessage setRecipients

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

Introduction

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

Prototype

public void setRecipients(Message.RecipientType type, String addresses) throws MessagingException 

Source Link

Document

Set the specified recipient type to the given addresses.

Usage

From source file:org.apache.james.protocols.smtp.netty.NettyStartTlsSMTPServerTest.java

@Test
public void startTlsShouldWorkWhenUsingJavamail() throws Exception {
    TestMessageHook hook = new TestMessageHook();
    server = createServer(createProtocol(Optional.<ProtocolHandler>of(hook)),
            Encryption.createStartTls(BogusSslContextFactory.getServerContext()));
    server.bind();//  www .j av  a2  s.  c o m
    SMTPTransport transport = null;

    try {
        InetSocketAddress bindedAddress = new ProtocolServerUtils(server).retrieveBindedAddress();

        Properties mailProps = new Properties();
        mailProps.put("mail.smtp.from", "test@localhost");
        mailProps.put("mail.smtp.host", bindedAddress.getHostName());
        mailProps.put("mail.smtp.port", bindedAddress.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);

        InternetAddress[] rcpts = new InternetAddress[] { new InternetAddress("valid@localhost") };
        MimeMessage message = new MimeMessage(mailSession);
        message.setFrom(new InternetAddress("test@localhost"));
        message.setRecipients(Message.RecipientType.TO, rcpts);
        message.setSubject("Testmail", "UTF-8");
        message.setText("Test.....");

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

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

        assertThat(hook.getQueued()).hasSize(1);
    } finally {
        if (transport != null) {
            transport.close();
        }
    }
}

From source file:org.socraticgrid.hl7.ucs.nifi.processor.SendEmail.java

private String sendEmail(String emailSubject, String fromEmail, String toEmail, String emailBody,
        String mimeType, String charset, String smtpServerUrl, String smtpServerPort, String username,
        String password, ServiceStatusController serviceStatusControllerService) throws Exception {

    String statusMessage = "Email sent successfully to " + toEmail;

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", smtpServerUrl);
    props.put("mail.smtp.port", smtpServerPort);

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }//from w  w  w . j  av  a 2  s. c o  m
    });
    try {
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromEmail));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
        message.setSubject(emailSubject);
        message.setContent(emailBody, mimeType + "; charset=" + charset);
        Transport.send(message);
        getLogger().info("Email sent successfully!");
        serviceStatusControllerService.updateServiceStatus("EMAIL", Status.AVAILABLE);
    } catch (MessagingException e) {
        serviceStatusControllerService.updateServiceStatus("EMAIL", Status.UNAVAILABLE);
        getLogger().error("Unable to send Email! Reason : " + e.getMessage(), e);
        statusMessage = "Unable to send Email! Reason : " + e.getMessage();
        throw new RuntimeException(e);
    }
    return statusMessage;
}

From source file:org.trpr.platform.integration.impl.email.SpringMailSender.java

/**
 * Interface method implementation. Sends an email using the specified values and the configured mail sender.
 * @see org.trpr.platform.integration.spi.email.MailSender#sendMail(java.lang.String, java.lang.String[], java.lang.String, java.net.URL)
 *///  w  ww .  j  a  v  a  2 s .c  o m
public void sendMail(final String senderAddress, final String subject, final String[] recipients,
        final String message, final URL attachmentURL) {
    MimeMessagePreparator preparator = new MimeMessagePreparator() {
        public void prepare(MimeMessage mimeMessage) throws Exception {
            InternetAddress[] recipientAddresses = new InternetAddress[recipients.length];
            for (int i = 0; i < recipientAddresses.length; i++) {
                recipientAddresses[i] = new InternetAddress(recipients[i]);
            }
            mimeMessage.setRecipients(Message.RecipientType.TO, recipientAddresses);
            mimeMessage.setFrom(new InternetAddress(senderAddress));
            mimeMessage.setSubject(subject);
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true); // multi-part flag is set to true for accommodating attachments
            if (attachmentURL != null) {
                helper.addAttachment(attachmentURL.getFile(), new FileSystemResource(attachmentURL.toString()));
            }
            helper.setText(message);
        }
    };
    this.mailSender.send(preparator);
}

From source file:org.pentaho.platform.plugin.services.email.EmailService.java

/**
 * Tests the provided email configuration by sending a test email. This will just indicate that the server
 * configuration is correct and a test email was successfully sent. It does not test the destination address.
 * /*w  ww.ja va2  s.co m*/
 * @param emailConfig
 *          the email configuration to test
 * @throws Exception
 *           indicates an error running the test (as in an invalid configuration)
 */
public String sendEmailTest(final IEmailConfiguration emailConfig) {
    final Properties emailProperties = new Properties();
    emailProperties.setProperty("mail.smtp.host", emailConfig.getSmtpHost());
    emailProperties.setProperty("mail.smtp.port", ObjectUtils.toString(emailConfig.getSmtpPort()));
    emailProperties.setProperty("mail.transport.protocol", emailConfig.getSmtpProtocol());
    emailProperties.setProperty("mail.smtp.starttls.enable", ObjectUtils.toString(emailConfig.isUseStartTls()));
    emailProperties.setProperty("mail.smtp.auth", ObjectUtils.toString(emailConfig.isAuthenticate()));
    emailProperties.setProperty("mail.smtp.ssl", ObjectUtils.toString(emailConfig.isUseSsl()));
    emailProperties.setProperty("mail.debug", ObjectUtils.toString(emailConfig.isDebug()));

    Session session = null;
    if (emailConfig.isAuthenticate()) {
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailConfig.getUserId(), emailConfig.getPassword());
            }
        };
        session = Session.getInstance(emailProperties, authenticator);
    } else {
        session = Session.getInstance(emailProperties);
    }

    String sendEmailMessage = "";
    try {
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(emailConfig.getDefaultFrom(), emailConfig.getFromName()));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailConfig.getDefaultFrom()));
        msg.setSubject(messages.getString("EmailService.SUBJECT"));
        msg.setText(messages.getString("EmailService.MESSAGE"));
        msg.setHeader("X-Mailer", "smtpsend");
        msg.setSentDate(new Date());
        Transport.send(msg);
        sendEmailMessage = "EmailTester.SUCESS";
    } catch (Exception e) {
        logger.error(messages.getString("EmailService.NOT_CONFIGURED"), e);
        sendEmailMessage = "EmailTester.FAIL";
    }
    return sendEmailMessage;
}

From source file:com.iorga.webappwatcher.watcher.RetentionLogWritingWatcher.java

protected void sendMailForEvent(final RetentionLogWritingEvent event) {
    log.info("Trying to send a mail for event " + event);

    new Thread(new Runnable() {
        @Override//  w ww. j  ava 2s  .  c  o  m
        public void run() {
            if (StringUtils.isEmpty(getMailSmtpHost()) || getMailSmtpPort() == null) {
                // no configuration defined, exiting
                log.error("Either SMTP host or port was not defined, not sending that mail");
                return;
            }
            // example from http://www.mkyong.com/java/javamail-api-sending-email-via-gmail-smtp-example/
            final Properties props = new Properties();
            props.put("mail.smtp.host", getMailSmtpHost());
            props.put("mail.smtp.port", getMailSmtpPort());
            final Boolean auth = getMailSmtpAuth();
            Authenticator authenticator = null;
            if (BooleanUtils.isTrue(auth)) {
                props.put("mail.smtp.auth", "true");
                authenticator = new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(getMailSmtpUsername(), getMailSmtpPassword());
                    }
                };
            }
            if (StringUtils.equalsIgnoreCase(getMailSmtpSecurityType(), "SSL")) {
                props.put("mail.smtp.socketFactory.port", getMailSmtpPort());
                props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            } else if (StringUtils.equalsIgnoreCase(getMailSmtpSecurityType(), "TLS")) {
                props.put("mail.smtp.starttls.enable", "true");
            }

            final Session session = Session.getDefaultInstance(props, authenticator);

            try {
                final MimeMessage message = new MimeMessage(session);
                message.setFrom(new InternetAddress(getMailFrom()));
                message.setRecipients(RecipientType.TO, InternetAddress.parse(getMailTo()));
                message.setSubject(event.getReason());
                if (event.getContext() != null) {
                    final StringBuilder contextText = new StringBuilder();
                    for (final Entry<String, Object> contextEntry : event.getContext().entrySet()) {
                        contextText.append(contextEntry.getKey()).append(" = ").append(contextEntry.getValue())
                                .append("\n");
                    }
                    message.setText(contextText.toString());
                } else {
                    message.setText("Context null");
                }

                Transport.send(message);
            } catch (final MessagingException e) {
                log.error("Problem while sending a mail", e);
            }
        }
    }, RetentionLogWritingWatcher.class.getSimpleName() + ":sendMailer").start(); // send mail in an async way
}

From source file:io.uengine.mail.MailAsyncService.java

@Async
public void trialCreated(String subject, String fromUser, String fromName, String toUser,
        InternetAddress[] toCC) {/*from   w ww. j  a  va  2s.  co  m*/
    Session session = setMailProperties(toUser);

    Map model = new HashMap();
    model.put("link", "http://www.uengine.io/my/license");

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/trial-created.vm", "UTF-8",
            model);

    try {
        InternetAddress from = new InternetAddress(fromUser, fromName);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(from);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));
        message.setSubject(subject);
        message.setContent(body, "text/html; charset=utf-8");
        if (toCC != null && toCC.length > 0)
            message.setRecipients(Message.RecipientType.CC, toCC);

        Transport.send(message);

        logger.info("{} ? ?? .", toUser);
    } catch (Exception e) {
        throw new ServiceException("??   .", e);
    }
}

From source file:io.uengine.mail.MailAsyncService.java

@Async
public void passwd(Long userId, String token, String subject, String fromUser, String fromName,
        final String toUser, InternetAddress[] toCC) {
    Session session = setMailProperties(toUser);

    Map model = new HashMap();
    model.put("link",
            MessageFormatter.arrayFormat("http://www.uengine.io/auth/passwdConfirm?userid={}&token={}",
                    new Object[] { Long.toString(userId), token }).getMessage());

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/passwd.vm", "UTF-8", model);

    try {/*from  w w w. jav  a 2 s  .  c o  m*/
        InternetAddress from = new InternetAddress(fromUser, fromName);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(from);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));
        message.setSubject(subject);
        message.setContent(body, "text/html; charset=utf-8");
        if (toCC != null && toCC.length > 0)
            message.setRecipients(Message.RecipientType.CC, toCC);

        Transport.send(message);

        logger.info("{} ? ?? .", toUser);
    } catch (Exception e) {
        throw new ServiceException("??   .", e);
    }
}

From source file:io.uengine.mail.MailAsyncService.java

@Async
public void registe(Long userId, String token, String subject, String fromUser, String fromName,
        final String toUser, InternetAddress[] toCC) {
    Session session = setMailProperties(toUser);

    Map model = new HashMap();
    model.put("link", MessageFormatter.arrayFormat("http://www.uengine.io/registe/confirm?userid={}&token={}",
            new Object[] { Long.toString(userId), token }).getMessage());

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/registe.vm", "UTF-8",
            model);// w  w  w  .  j  a va2 s  . co m

    try {
        InternetAddress from = new InternetAddress(fromUser, fromName);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(from);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));
        message.setSubject(subject);
        message.setContent(body, "text/html; charset=utf-8");
        if (toCC != null && toCC.length > 0)
            message.setRecipients(Message.RecipientType.CC, toCC);

        Transport.send(message);

        logger.info("{} ? ?? .", toUser);
    } catch (Exception e) {
        throw new ServiceException("??   .", e);
    }
}

From source file:io.uengine.mail.MailAsyncService.java

@Async
public void download(String type, String version, String token, String subject, String fromUser,
        String fromName, final String toUser, final String toName, InternetAddress[] toCC) {
    Session session = setMailProperties(toUser);

    Map model = new HashMap();
    model.put("link",
            MessageFormatter.arrayFormat("http://www.uengine.io/download/get?type={}&version={}&token={}",
                    new Object[] { type, version, token }).getMessage());
    model.put("name", toName);

    String body = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "mail/download.vm", "UTF-8",
            model);// w  ww  . j  a  v  a  2s . co  m

    try {
        InternetAddress from = new InternetAddress(fromUser, fromName);
        MimeMessage message = new MimeMessage(session);
        message.setFrom(from);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toUser));
        message.setSubject(subject);
        message.setContent(body, "text/html; charset=utf-8");
        if (toCC != null && toCC.length > 0)
            message.setRecipients(Message.RecipientType.CC, toCC);

        Transport.send(message);

        logger.info("{} ? ?? .", toUser);
    } catch (Exception e) {
        throw new ServiceException("??   .", e);
    }
}

From source file:com.anteam.alert.email.service.EmailAntlert.java

@Override
public boolean send(AntlertMessage antlertMsg) {

    MimeMessage mimeMsg; // MIME

    // from?to?//w  w w  .jav  a  2  s  .c om
    mimeMsg = new javax.mail.internet.MimeMessage(mailSession);

    try {
        // ?
        mimeMsg.setFrom(sender);
        // 
        mimeMsg.setRecipients(RecipientType.TO, receivers);
        // 
        mimeMsg.setSubject(antlertMsg.getTitle(), CHARSET);

        // 
        MimeBodyPart messageBody = new MimeBodyPart();
        messageBody.setContent(antlertMsg.getContent(), CONTENT_MIME_TYPE);

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBody);
        mimeMsg.setContent(multipart);

        // ??
        mimeMsg.setSentDate(new Date());
        mimeMsg.saveChanges();

        // ??
        Transport.send(mimeMsg);
    } catch (MessagingException e) {
        logger.error("???", e);
        return false;
    }
    return true;
}