Example usage for javax.mail.internet MimeMessage addRecipients

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

Introduction

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

Prototype

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

Source Link

Document

Add the given addresses to the specified recipient type.

Usage

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

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

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

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

        BodyPart part = new MimeBodyPart();
        part.setText(messageText);/*from   w  w  w  . j  ava2s.c  o  m*/
        multipart.addBodyPart(part);

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

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

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

From source file:org.talend.dataprep.api.service.mail.MailFeedbackSender.java

@Override
public void send(String subject, String body, String sender) {
    try {/*from w  w  w.  j  a v  a 2s . c o  m*/
        final String recipientList = StringUtils.join((new HashSet<>(Arrays.asList(recipients))).toArray(),
                ',');
        subject = subjectPrefix + subject;
        body = bodyPrefix + "<br/>" + body + "<br/>" + bodySuffix;

        InternetAddress from = new InternetAddress(this.sender);
        InternetAddress replyTo = new InternetAddress(sender);

        Properties p = new Properties();
        p.put("mail.smtp.host", smtpHost);
        p.put("mail.smtp.port", smtpPort);
        p.put("mail.smtp.starttls.enable", "true");
        p.put("mail.smtp.auth", "true");

        MailAuthenticator authenticator = new MailAuthenticator(userName, password);
        Session sendMailSession = Session.getInstance(p, authenticator);

        MimeMessage msg = new MimeMessage(sendMailSession);
        msg.setFrom(from);
        msg.setReplyTo(new Address[] { replyTo });
        msg.addRecipients(Message.RecipientType.TO, recipientList);

        msg.setSubject(subject, "UTF-8");
        msg.setSentDate(new Date());
        Multipart mainPart = new MimeMultipart();
        BodyPart html = new MimeBodyPart();
        html.setContent(body, "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        msg.setContent(mainPart);
        Transport.send(msg);

        LOGGER.debug("Sending mail:'{}' to '{}'", subject, recipients);
    } catch (Exception e) {
        throw new TDPException(APIErrorCodes.UNABLE_TO_SEND_MAIL, e);
    }
}

From source file:com.mgmtp.jfunk.core.reporting.EmailReporter.java

private void sendMessage(final String content) {
    try {/*  www. ja v  a 2  s . co m*/
        MimeMessage msg = new MimeMessage(sessionProvider.get());
        msg.setSubject("jFunk E-mail Report");
        msg.addRecipients(Message.RecipientType.TO, recipientsProvider.get());

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(content, "text/html; charset=UTF-8");

        MimeMultipart multipart = new MimeMultipart("related");
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("check.gif")));
        messageBodyPart.setHeader("Content-ID", "<check>");
        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setDataHandler(new DataHandler(getClass().getResource("error.gif")));
        messageBodyPart.setHeader("Content-ID", "<error>");
        multipart.addBodyPart(messageBodyPart);

        msg.setContent(multipart);

        smtpClientProvider.get().send(msg);

        int anzahlRecipients = msg.getAllRecipients().length;
        log.info(
                "Report e-mail was sent to " + anzahlRecipients + " recipient(s): " + recipientsProvider.get());
    } catch (MessagingException e) {
        log.error("Error while creating report e-mail", e);
    } catch (MailException e) {
        log.error("Error while sending report e-mail", e);
    }
}

From source file:ftpclient.FTPManager.java

public boolean sendUserMail(String uploadedFileName) {
    if (settings != null) {
        try {//from   w ww .j a v a  2s .  c  o m
            String userEmail = db.getUserEmail(uid);
            Properties props = System.getProperties();
            props.setProperty("mail.smtp.host", settings.getSenderEmailHost());
            props.setProperty("mail.smtp.auth", "true");
            //            props.put("mail.smtp.starttls.enable", "true");
            //            props.put("mail.smtp.port", "587");
            Session s = Session.getDefaultInstance(props, new Authenticator() {

                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(settings.getSenderLogin(),
                            new String(settings.getSenderPassword()));
                }
            });
            MimeMessage msg = new MimeMessage(s);
            msg.setFrom(settings.getSenderEmail());
            msg.addRecipients(Message.RecipientType.TO, userEmail);
            msg.setSubject("FTP action");
            msg.setText("You have succesfully uploaded file " + uploadedFileName);
            Transport.send(msg);
            return true;
        } catch (MessagingException ex) {
            Logger.getLogger(FTPManager.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    } else {
        return false;
    }
}

From source file:com.mgmtp.perfload.perfalyzer.reporting.email.EmailReporter.java

private void sendMessage(final String subject, final String content) {
    try {/*w w  w.j av  a2  s.  co m*/
        Session session = (authenticator != null) ? Session.getInstance(smtpProps, authenticator)
                : Session.getInstance(smtpProps);

        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromAddress));
        msg.setSubject(subject);
        msg.addRecipients(Message.RecipientType.TO, on(',').join(toAddresses));
        msg.setText(content, UTF_8.name(), "html");

        Transport.send(msg);
    } catch (MessagingException e) {
        log.error("Error while creating report e-mail", e);
    }
}

From source file:org.mobicents.servlet.restcomm.email.EmailService.java

EmailResponse send(final Mail mail) {
    try {/*from   w ww. j  ava 2  s  .  co  m*/
        InternetAddress from;
        if (mail.from() != null || !mail.from().equalsIgnoreCase("")) {
            from = new InternetAddress(mail.from());
        } else {
            from = new InternetAddress(user);
        }
        final InternetAddress to = new InternetAddress(mail.to());
        final MimeMessage email = new MimeMessage(session);
        email.setFrom(from);
        email.addRecipient(Message.RecipientType.TO, to);
        email.setSubject(mail.subject());
        email.setText(mail.body());
        email.addRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.cc(), false));
        email.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(mail.bcc(), false));
        Transport.send(email);
        return new EmailResponse(mail);
    } catch (final MessagingException exception) {
        logger.error(exception.getMessage(), exception);
        return new EmailResponse(exception, exception.getMessage());
    }
}

From source file:net.sourceforge.vulcan.mailer.MessageAssembler.java

public MimeMessage constructMessage(String subscribers, ConfigDto config, ProjectStatusDto status, String html)
        throws MessagingException, AddressException {

    final MimeMessage message = new MimeMessage(mailSession);

    message.setSentDate(new Date());
    message.setFrom(new InternetAddress(config.getSenderAddress()));

    if (isNotBlank(config.getReplyToAddress())) {
        message.setReplyTo(InternetAddress.parse(config.getReplyToAddress()));
    }//  ww  w .ja  v a  2 s .  co m
    message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(subscribers));

    message.setSubject(status.getName() + ": " + status.getStatus());

    final Multipart multipart = new MimeMultipart();

    html = html.replaceAll("\\r", "");

    addMultipartBody(multipart, "text/html; charset=UTF-8", html);

    message.setContent(multipart);

    return message;
}

From source file:org.restcomm.connect.email.EmailService.java

EmailResponse sendEmailSsL(final Mail mail) {
    try {// ww w  . j  a v a 2s . co  m
        InternetAddress from;
        if (mail.from() != null || !mail.from().equalsIgnoreCase("")) {
            from = new InternetAddress(mail.from());
        } else {
            from = new InternetAddress(user);
        }
        final InternetAddress to = new InternetAddress(mail.to());
        final MimeMessage email = new MimeMessage(session);
        email.setFrom(from);
        email.addRecipient(Message.RecipientType.TO, to);
        email.setSubject(mail.subject());
        email.setText(mail.body());
        email.addRecipients(Message.RecipientType.CC, InternetAddress.parse(mail.cc(), false));
        email.addRecipients(Message.RecipientType.BCC, InternetAddress.parse(mail.bcc(), false));
        //Transport.send(email);
        transport.connect(host, Integer.parseInt(port), user, password);
        transport.sendMessage(email, email.getRecipients(Message.RecipientType.TO));
        return new EmailResponse(mail);
    } catch (final MessagingException exception) {
        logger.error(exception.getMessage(), exception);
        return new EmailResponse(exception, exception.getMessage());
    }
}

From source file:org.openiam.idm.srvc.msg.service.MailSenderClient.java

public void send(Message msg) {
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.transport.protocol", "smtp");

    if (username != null && !username.isEmpty()) {
        properties.setProperty("mail.user", username);
        properties.setProperty("mail.password", password);
    }//from  w ww.j a  v  a2 s .c  om

    if (port != null && !port.isEmpty()) {
        properties.setProperty("mail.smtp.port", port);
    }

    Session session = Session.getDefaultInstance(properties);
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(msg.getFrom());
        if (msg.getTo().size() > 1) {
            List<InternetAddress> addresses = msg.getTo();
            message.addRecipients(TO, addresses.toArray(new Address[addresses.size()]));
        } else {
            message.addRecipient(TO, msg.getTo().get(0));
        }
        if (msg.getBcc() != null && msg.getBcc().size() != 0) {
            if (msg.getTo().size() > 1) {
                List<InternetAddress> addresses = msg.getBcc();
                message.addRecipients(BCC, addresses.toArray(new Address[addresses.size()]));
            } else {
                message.addRecipient(TO, msg.getBcc().get(0));
            }
        }
        if (msg.getCc() != null && msg.getCc().size() > 0) {
            if (msg.getCc().size() > 1) {
                List<InternetAddress> addresses = msg.getCc();
                message.addRecipients(CC, addresses.toArray(new Address[addresses.size()]));
            } else {
                message.addRecipient(CC, msg.getCc().get(0));
            }
        }
        message.setSubject(msg.getSubject(), "UTF-8");
        MimeBodyPart mbp1 = new MimeBodyPart();
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();

        if (msg.getBodyType() == Message.BodyType.HTML_TEXT) {
            mbp1.setContent(msg.getBody(), "text/html");
        } else {
            mbp1.setText(msg.getBody(), "UTF-8");
        }
        if (port != null && !port.isEmpty()) {
            properties.setProperty("mail.smtp.port", port);
        }
        mp.addBodyPart(mbp1);
        if (msg.getAttachments().size() > 0) {
            for (String fileName : msg.getAttachments()) {
                // create the second message part
                MimeBodyPart mbpFile = new MimeBodyPart();
                // attach the file to the message
                FileDataSource fds = new FileDataSource(fileName);
                mbpFile.setDataHandler(new DataHandler(fds));
                mbpFile.setFileName(fds.getName());

                mp.addBodyPart(mbpFile);
            }
        }
        // add the Multipart to the message
        message.setContent(mp);

        if (username != null && !username.isEmpty()) {
            properties.setProperty("mail.user", username);
            properties.setProperty("mail.password", password);
            properties.put("mail.smtp.auth", auth);
            properties.put("mail.smtp.starttls.enable", starttls);
            Transport mailTransport = session.getTransport();
            mailTransport.connect(host, username, password);
            mailTransport.sendMessage(message, message.getAllRecipients());

        } else {
            Transport.send(message);
            log.debug("Message successfully sent.");
        }
    } catch (Throwable e) {
        log.error("Exception while sending mail", e);
    }
}

From source file:org.patientview.monitoring.ImportMonitor.java

public static void sendEmail(String from, String[] to, String[] bcc, String subject, String body) {
    if (StringUtils.isBlank(from)) {
        throw new IllegalArgumentException("Cannot send mail missing 'from'");
    }//from w  w w . j a v a  2s . c o  m

    if ((to == null || to.length == 0) && (bcc == null || bcc.length == 0)) {
        throw new IllegalArgumentException("Cannot send mail missing recipients");
    }

    if (StringUtils.isBlank(subject)) {
        throw new IllegalArgumentException("Cannot send mail missing 'subject'");
    }

    if (StringUtils.isBlank(body)) {
        throw new IllegalArgumentException("Cannot send mail missing 'body'");
    }

    ApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] { "classpath*:context-standalone.xml" });

    JavaMailSender javaMailSender = (JavaMailSender) context.getBean("javaMailSender");

    MimeMessage message = javaMailSender.createMimeMessage();
    MimeMessageHelper messageHelper;

    try {
        messageHelper = new MimeMessageHelper(message, true);
        messageHelper.setTo(to);
        if (bcc != null && bcc.length > 0) {
            Address[] bccAddresses = new Address[bcc.length];
            for (int i = 0; i < bcc.length; i++) {
                bccAddresses[i] = new InternetAddress(bcc[i]);
            }
            message.addRecipients(Message.RecipientType.BCC, bccAddresses);
        }
        messageHelper.setFrom(from);
        messageHelper.setSubject(subject);
        messageHelper.setText(body, false); // Note: the second param indicates to send plaintext

        javaMailSender.send(messageHelper.getMimeMessage());

        LOGGER.info("Sent an email about Importer issues. From: {} To: {}", from, Arrays.toString(to));
    } catch (Exception e) {
        LOGGER.error("Could not send email: {}", e);
    }
}