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:controllerClasses.security.SiteuserControl.java

private void sendMail(String email, String subject, String body)
        throws NamingException, javax.mail.MessagingException {

    javax.mail.internet.MimeMessage message = new javax.mail.internet.MimeMessage(mailAOSMail);
    message.setSubject(subject);//from  www. j a va  2s . c o  m
    message.setRecipients(javax.mail.Message.RecipientType.TO,
            javax.mail.internet.InternetAddress.parse(email, false));
    message.setContent(body, "text/html");
    javax.mail.Transport.send(message);
}

From source file:atd.backend.Register.java

public void sendRegMail(Klant k) throws IOException {
    Properties propMail = new Properties();
    InputStream config = null;/*ww w.ja  v a  2 s  .co m*/
    config = new URL(CONFIG_URL).openStream();
    propMail.load(config);

    Properties props = new Properties();
    props.put("mail.smtp.host", propMail.getProperty("host"));
    props.put("mail.smtp.port", 465);
    props.put("mail.smtp.ssl.enable", true);
    Session mailSession = Session.getInstance(props);
    try {
        Logger.getLogger("atd.log").info("Stuurt mail naar: " + k.getEmail());
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(propMail.getProperty("email"), propMail.getProperty("mailName")));
        msg.setRecipients(Message.RecipientType.TO, k.getEmail());
        msg.setSubject("Uw account is aangemaakt");
        msg.setSentDate(Calendar.getInstance().getTime());
        msg.setContent("Beste " + k.getNaam() + ", \n\nUw account " + k.getUsername()
                + " is aangemaakt, U kunt inloggen op de <a href='https://atd.plebian.nl'>ATD website</a>\n",
                "text/html; charset=utf-8");
        // TODO: Heeft OAUTH nodig, maarja we zijn al niet erg netjes met
        // wachtwoorden
        Transport.send(msg, propMail.getProperty("email"), propMail.getProperty("password"));
    } catch (Exception e) {
        Logger.getLogger("atd.log").warning("send failed: " + e.getMessage());
    }
}

From source file:org.awknet.commons.mail.Mail.java

public void send() throws AddressException, MessagingException, FileNotFoundException, IOException {
    int count = recipientsTo.size() + recipientsCc.size() + recipientsBcc.size();
    if (count == 0)
        return;/*  ww  w .  j  ava  2s  . c  o m*/

    deleteDuplicates();

    Properties javaMailProperties = new Properties();

    if (fileName.equals("") || fileName == null)
        fileName = DEFAULT_PROPERTIES_FILE;

    javaMailProperties.load(getClass().getResourceAsStream(fileName));

    final String mailUsername = javaMailProperties.getProperty("mail.autentication.username");
    final String mailPassword = javaMailProperties.getProperty("mail.autentication.password");
    final String mailFrom = javaMailProperties.getProperty("mail.autentication.mail_from");

    Session session = Session.getInstance(javaMailProperties, new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(mailUsername, mailPassword);
        }
    });

    final MimeMessage msg = new MimeMessage(session);

    msg.setFrom(new InternetAddress(mailFrom));
    msg.setRecipients(Message.RecipientType.TO, getToRecipientsArray());
    msg.setRecipients(Message.RecipientType.CC, getCcRecipientsArray());
    msg.setRecipients(Message.RecipientType.BCC, getBccRecipientsArray());
    msg.setSentDate(new Date());
    msg.setSubject(mailSubject);
    msg.setText(mailText, "UTF-8", "html");
    // msg.setText(mailText); //OLD WAY
    new Thread(new Runnable() {
        public void run() {
            try {
                Transport.send(msg);
                Logger.getLogger(Mail.class.getName()).log(Level.INFO, "email was sent successfully!");
            } catch (MessagingException ex) {
                Logger.getLogger(Mail.class.getName()).log(Level.SEVERE, "Cant send email!", ex);
            }
        }
    }).start();
}

From source file:com.enjoyxstudy.selenium.autoexec.mail.MailSender.java

/**
 * @param runner// w  w  w.j  av  a 2s  .c o  m
 * @param resultDir
 * @throws MessagingException
 * @throws IOException
 */
public void send(MultiHTMLSuiteRunner runner, File resultDir) throws MessagingException, IOException {

    MimeMessage mimeMessage = new MimeMessage(session);

    mimeMessage.setHeader("Content-Transfer-Encoding", "7bit");

    // To
    mimeMessage.setRecipients(Message.RecipientType.TO, InternetAddress.parse(config.getTo()));

    // From
    mimeMessage.setFrom(new InternetAddress(config.getFrom()));

    HashMap<String, Object> context = new HashMap<String, Object>();
    context.put("result", runner.getResult() ? "passed" : "failed");
    context.put("passedCount", new Integer(runner.getPassedCount()));
    context.put("failedCount", new Integer(runner.getFailedCount()));
    context.put("totalCount", new Integer(runner.getHtmlSuiteList().size()));
    context.put("startTime", new Date(runner.getStartTime()));
    context.put("endTime", new Date(runner.getEndTime()));
    context.put("htmlSuites", runner.getHtmlSuiteList());

    // subject
    mimeMessage.setSubject(TemplateUtils.merge(config.getSubject(), context), config.getCharset());

    // multipart message
    MimeMultipart content = new MimeMultipart();

    MimeBodyPart body = new MimeBodyPart();
    body.setText(TemplateUtils.merge(config.getBody(), context), config.getCharset());
    content.addBodyPart(body);

    File resultArchive = createResultArchive(resultDir);

    MimeBodyPart attachmentFile = new MimeBodyPart();
    attachmentFile.setDataHandler(new DataHandler(new FileDataSource(resultArchive)));
    attachmentFile.setFileName(RESULT_ARCHIVE_FILE);
    content.addBodyPart(attachmentFile);

    mimeMessage.setContent(content);

    // send mail
    _send(mimeMessage);
}

From source file:com.bia.yahoomailjava.YahooMailService.java

/**
 *
 * @param addressTo//from   www  .  j a v  a2s . co  m
 * @param subject
 * @param message
 *
 */
private void send(InternetAddress[] addressTo, String subject, String message) {
    try {
        MimeMessage msg = new MimeMessage(createSession());
        msg.setFrom(new InternetAddress(USERNAME));
        msg.setRecipients(MimeMessage.RecipientType.TO, addressTo);
        msg.setSubject(subject);
        msg.setText(message);
        Transport.send(msg);
    } catch (Exception ex) {
        //logger.warn(ex.getMessage(), ex);
        throw new RuntimeException(ex);
    }
}

From source file:com.brienwheeler.svc.email.impl.EmailService.java

/**
 * This is a private method (rather than having the public template method
 * call the public non-template method) to prevent inaccurate MonitoredWork
 * operation counts.//from  w w  w  .ja v a  2  s. c  o m
 * 
 * @param recipient
 * @param subject
 * @param body
 */
private void doSendEmail(EmailAddress recipient, String subject, String body) {
    ValidationUtils.assertNotNull(recipient, "recipient cannot be null");
    subject = ValidationUtils.assertNotEmpty(subject, "subject cannot be empty");
    body = ValidationUtils.assertNotEmpty(body, "body cannot be empty");

    try {
        MimeMessage message = new MimeMessage(mailSession);
        message.setFrom(new InternetAddress(fromAddress.getAddress()));
        message.setRecipients(Message.RecipientType.TO, recipient.getAddress());
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setText(body);
        Transport.send(message);
        log.info("sent email to " + recipient.getAddress() + " (" + subject + ")");
    } catch (MessagingException e) {
        throw new ServiceOperationException(e);
    }
}

From source file:io.kamax.mxisd.threepid.connector.email.EmailSmtpConnector.java

@Override
public void send(String senderAddress, String senderName, String recipient, String content) {
    if (StringUtils.isBlank(senderAddress)) {
        throw new FeatureNotAvailable("3PID Email identity: sender address is empty - "
                + "You must set a value for notifications to work");
    }/* w w w  .  j a  v  a  2s.c o m*/

    if (StringUtils.isBlank(content)) {
        throw new InternalServerError("Notification content is empty");
    }

    try {
        InternetAddress sender = new InternetAddress(senderAddress, senderName);
        MimeMessage msg = new MimeMessage(session, IOUtils.toInputStream(content, StandardCharsets.UTF_8));
        msg.setHeader("X-Mailer", "mxisd"); // FIXME set version
        msg.setSentDate(new Date());
        msg.setFrom(sender);
        msg.setRecipients(Message.RecipientType.TO, recipient);
        msg.saveChanges();

        log.info("Sending invite to {} via SMTP using {}:{}", recipient, cfg.getHost(), cfg.getPort());
        SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
        transport.setStartTLS(cfg.getTls() > 0);
        transport.setRequireStartTLS(cfg.getTls() > 1);

        log.info("Connecting to {}:{}", cfg.getHost(), cfg.getPort());
        transport.connect(cfg.getHost(), cfg.getPort(), cfg.getLogin(), cfg.getPassword());
        try {
            transport.sendMessage(msg, InternetAddress.parse(recipient));
            log.info("Invite to {} was sent", recipient);
        } finally {
            transport.close();
        }
    } catch (UnsupportedEncodingException | MessagingException e) {
        throw new RuntimeException("Unable to send e-mail invite to " + recipient, e);
    }
}

From source file:com.thinkbiganalytics.metadata.sla.SlaEmailService.java

/**
 * Send an email//ww  w . j a v  a 2s. c  o m
 *
 * @param to      the user(s) to send the email to
 * @param subject the subject of the email
 * @param body    the email body
 */
public void sendMail(String to, String subject, String body) {

    try {
        if (testConnection()) {
            MimeMessage message = mailSender.createMimeMessage();
            String fromAddress = StringUtils.defaultIfBlank(emailConfiguration.getFrom(),
                    emailConfiguration.getUsername());
            message.setFrom(new InternetAddress(fromAddress));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);
            message.setText(body);
            mailSender.send(message);
            log.debug("Email send to {}", to);
        }
    } catch (MessagingException ex) {
        log.error("Exception while sending mail : {}", ex.getMessage());
        Throwables.propagate(ex);

    }
}

From source file:org.mule.transport.email.transformers.StringToEmailMessage.java

@Override
public Object transformMessage(MuleMessage message, String outputEncoding) throws TransformerException {
    String endpointAddress = endpoint.getEndpointURI().getAddress();
    SmtpConnector connector = (SmtpConnector) endpoint.getConnector();
    String to = lookupProperty(message, MailProperties.TO_ADDRESSES_PROPERTY, endpointAddress);
    String cc = lookupProperty(message, MailProperties.CC_ADDRESSES_PROPERTY, connector.getCcAddresses());
    String bcc = lookupProperty(message, MailProperties.BCC_ADDRESSES_PROPERTY, connector.getBccAddresses());
    String from = lookupProperty(message, MailProperties.FROM_ADDRESS_PROPERTY, connector.getFromAddress());
    String replyTo = lookupProperty(message, MailProperties.REPLY_TO_ADDRESSES_PROPERTY,
            connector.getReplyToAddresses());
    String subject = lookupProperty(message, MailProperties.SUBJECT_PROPERTY, connector.getSubject());
    String contentType = lookupProperty(message, MailProperties.CONTENT_TYPE_PROPERTY,
            connector.getContentType());

    Properties headers = new Properties();
    Properties customHeaders = connector.getCustomHeaders();

    if (customHeaders != null && !customHeaders.isEmpty()) {
        headers.putAll(customHeaders);//from www  .  j a  va  2  s.  c  o  m
    }

    Properties otherHeaders = message.getOutboundProperty(MailProperties.CUSTOM_HEADERS_MAP_PROPERTY);
    if (otherHeaders != null && !otherHeaders.isEmpty()) {
        //TODO Whats going on here?
        //                final MuleContext mc = context.getMuleContext();
        //                for (Iterator iterator = message.getPropertyNames().iterator(); iterator.hasNext();)
        //                {
        //                    String propertyKey = (String) iterator.next();
        //                    mc.getRegistry().registerObject(propertyKey, message.getProperty(propertyKey), mc);
        //                }
        headers.putAll(templateParser.parse(new TemplateParser.TemplateCallback() {
            public Object match(String token) {
                return muleContext.getRegistry().lookupObject(token);
            }
        }, otherHeaders));

    }

    if (logger.isDebugEnabled()) {
        StringBuffer buf = new StringBuffer();
        buf.append("Constructing email using:\n");
        buf.append("To: ").append(to);
        buf.append(", From: ").append(from);
        buf.append(", CC: ").append(cc);
        buf.append(", BCC: ").append(bcc);
        buf.append(", Subject: ").append(subject);
        buf.append(", ReplyTo: ").append(replyTo);
        buf.append(", Content type: ").append(contentType);
        buf.append(", Payload type: ").append(message.getPayload().getClass().getName());
        buf.append(", Custom Headers: ").append(MapUtils.toString(headers, false));
        logger.debug(buf.toString());
    }

    try {
        MimeMessage email = new MimeMessage(
                ((SmtpConnector) endpoint.getConnector()).getSessionDetails(endpoint).getSession());

        email.setRecipients(Message.RecipientType.TO, MailUtils.stringToInternetAddresses(to));

        // sent date
        email.setSentDate(Calendar.getInstance().getTime());

        if (StringUtils.isNotBlank(from)) {
            email.setFrom(MailUtils.stringToInternetAddresses(from)[0]);
        }

        if (StringUtils.isNotBlank(cc)) {
            email.setRecipients(Message.RecipientType.CC, MailUtils.stringToInternetAddresses(cc));
        }

        if (StringUtils.isNotBlank(bcc)) {
            email.setRecipients(Message.RecipientType.BCC, MailUtils.stringToInternetAddresses(bcc));
        }

        if (StringUtils.isNotBlank(replyTo)) {
            email.setReplyTo(MailUtils.stringToInternetAddresses(replyTo));
        }

        email.setSubject(subject, outputEncoding);

        for (Iterator iterator = headers.entrySet().iterator(); iterator.hasNext();) {
            Map.Entry entry = (Map.Entry) iterator.next();
            email.setHeader(entry.getKey().toString(), entry.getValue().toString());
        }

        setContent(message.getPayload(), email, contentType, message);

        return email;
    } catch (Exception e) {
        throw new TransformerException(this, e);
    }
}

From source file:com.predic8.membrane.core.interceptor.authentication.session.EmailTokenProvider.java

private void sendEmail(String sender, String recipient, String subject, String text) {
    try {//w  w w .  j a va 2  s  . c  om
        Properties props = System.getProperties();
        props.put("mail.smtp.port", "" + smtpPort);
        props.put("mail.smtp.socketFactory.port", "" + smtpPort);
        if (ssl) {
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.starttls.required", "true");
        }
        if (smtpUser != null) {
            props.put("mail.smtp.auth", "true");
        }

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

        final MimeMessage msg = new MimeMessage(session);

        msg.setFrom(new InternetAddress(sender));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, false));
        msg.setSubject(subject);
        msg.setText(text, Constants.UTF_8);
        msg.setSentDate(new Date());

        SMTPTransport t = (SMTPTransport) session.getTransport(ssl ? "smtps" : "smtp");
        t.connect(smtpHost, smtpUser, smtpPassword);
        t.sendMessage(msg, msg.getAllRecipients());
        t.close();
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}