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:com.hg.ecommerce.util.MailUtil.java

/**
 * This method is used to send a Message with a pre-defined
 * mime-type.//from   ww  w.ja v a 2s .  c om
 *
 * @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:com.eatcodesleep.web.MailRestController.java

@RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public String sendMail(@RequestBody final TextEmail textEmail) {
    javaMailSender.send((MimeMessage mimeMessage) -> {
        mimeMessage.setFrom(textEmail.getFromAddress());
        mimeMessage.setRecipients(Message.RecipientType.TO, textEmail.getToAddressesAsCommaSeparatedString());
        mimeMessage.setText(textEmail.getMessage());
    });/*from  w w  w  . j a  v  a2 s .c  o  m*/
    return "Success!!!";
}

From source file:edu.washington.iam.tools.IamMailSender.java

private MimeMessage genMimeMessage(IamMailMessage msg) {
    MimeMessage mime = mailSender.createMimeMessage();
    try {/*  w  w w  . j  a v  a2  s. com*/
        mime.setRecipients(RecipientType.TO, InternetAddress.parse(msg.getTo()));
        mime.setSubject(msg.makeSubstitutions(msg.getSubject()));
        mime.setReplyTo(InternetAddress.parse(replyTo));
        mime.setFrom(new InternetAddress(msg.getFrom()));
        mime.addHeader("X-Auto-Response-Suppress", "NDR, OOF, AutoReply");
        mime.addHeader("Precedence", "Special-Delivery, never-bounce");
        mime.setText(msg.makeSubstitutions(msg.getText()));
    } catch (MessagingException e) {
        log.error("iam mail build fails: " + e);
    }
    return mime;
}

From source file:br.com.valecard.listeners.SendMailListener.java

@Override
public void onApplicationEvent(SendMailEvent event) {
    MimeMessage mm = mailSender.createMimeMessage();
    final String property = event.getProperty();
    try {//from   ww  w.  ja va 2 s.c om
        mm.setRecipients(Message.RecipientType.TO, property);
        mm.setText(property);
        //            mm.addHeader(XMC_TRACK, track);
        //            mm.addHeader(XMC_TEMPLATE, property);
        //            mm.addHeader(XMC_MERGE_VARS, mergeVars);
    } catch (MessagingException ex) {
        LOG.log(Level.WARNING, ex.getMessage(), ex);
    }
    try {
        mailSender.send(mm);
    } catch (MailException ex) {
        LOG.log(Level.WARNING, ex.getMessage(), ex);
    }
}

From source file:com.mycompany.login.mb.EmailBean.java

public void envia() throws AddressException, MessagingException {
    Session session = Session.getInstance(this.propriedades, this.authentication);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress("anderson.freitas@lifemed.com.br"));
    message.setRecipients(Message.RecipientType.TO, "anderson.freitas@lifemed.com.br");
    message.setSentDate(new Date());
    message.setSubject("Teste envio jsf");
    message.setContent("Sua solicitao foi aprovada: OS n" + this.os, "text/plain");

    Transport.send(message);//from   w  ww .j av a  2  s  .com

}

From source file:de.hybris.platform.cuppytrail.forgotpassword.actions.SendEmailAction.java

@Override
public void executeAction(final ForgotPasswordProcessModel process) throws RetryLaterException, Exception {
    final EmailMessageModel emailMessage = process.getEmailMessage();
    final MimeMessagePreparator preparator = new MimeMessagePreparator() {

        @Override//from   w w w.j  av a 2s  .  c o m
        public void prepare(final MimeMessage message) throws Exception {
            message.setSubject(emailMessage.getSubject());
            message.setText(emailMessage.getBody());
            message.setRecipients(RecipientType.TO, emailMessage.getRecipientAddress());
        }

    };
    mailSender.send(preparator);
}

From source file:com.emc.plants.service.impl.MailerBean.java

/** 
 * Create a mail message and send it./*from w  w  w  .  j  a  v  a 2s  . c  o m*/
 *
 * @param customerInfo  Customer information.
 * @param orderKey
 * @throws MailerAppException
 */
public void createAndSendMail(CustomerInfo customerInfo, long orderKey) throws MailerAppException {
    try {
        EMailMessage eMessage = new EMailMessage(createSubjectLine(orderKey), createMessage(orderKey),
                customerInfo.getCustomerID());
        Util.debug("Sending message" + "\nTo: " + eMessage.getEmailReceiver() + "\nSubject: "
                + eMessage.getSubject() + "\nContents: " + eMessage.getHtmlContents());

        //Session mailSession = (Session) Util.getInitialContext().lookup(MAIL_SESSION);

        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom();

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(eMessage.getEmailReceiver(), false));

        msg.setSubject(eMessage.getSubject());
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setText(eMessage.getHtmlContents(), "us-ascii");
        msg.setHeader("X-Mailer", "JavaMailer");
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp);
        msg.setContent(mp);
        msg.setSentDate(new Date());

        Transport.send(msg);

        Util.debug("\nMail sent successfully.");
    } catch (Exception e) {
        Util.debug("Error sending mail. Have mail resources been configured correctly?");
        Util.debug("createAndSendMail exception : " + e);
        e.printStackTrace();
        throw new MailerAppException("Failure while sending mail");
    }
}

From source file:com.unilever.audit.services2.ForgetPassword.java

@GET
@Path("Email/{email}")
@Produces("application/json")
public String LoginIn(@PathParam("email") String email) throws IOException {
    boolean status = true;
    String error = null;//from   www. ja  v a 2 s .c  om
    JSONObject result = new JSONObject();

    Map<String, Object> hm = new HashMap<String, Object>();
    hm.put("email", email);
    Merchandisers merchidisers = (Merchandisers) merchandisersFacadeREST
            .findOneByQuery("Merchandisers.findByEmail", hm);
    if (merchidisers == null) {
        status = false;
        error = "invalid email";
    } else {
        Properties props = new Properties();
        final String from = "";
        final String password = "";
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.password", password);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, password);
            }
        });
        session.setDebug(true);
        try {
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom();
            msg.setRecipients(Message.RecipientType.TO, email);
            msg.setSubject("Unilever Confirmation");
            msg.setSentDate(new Date());
            msg.setText("");
            Transport.send(msg);
        } catch (MessagingException ex) {
            //  status = false;
            //  error="Error Sending Email";
            ex.printStackTrace();
        }
    }
    result.put("status", status);
    result.put("error", error);
    System.out.println("----------------" + result.toString());
    return result.toString();
}

From source file:be.fedict.eid.dss.model.bean.TaskMDB.java

private void sendMail(String mailTo, String subject, String messageBody, String attachmentMimetype,
        byte[] attachment) {
    LOG.debug("sending email to " + mailTo + " with subject \"" + subject + "\"");
    String smtpServer = this.configuration.getValue(ConfigProperty.SMTP_SERVER, String.class);
    if (null == smtpServer || smtpServer.trim().isEmpty()) {
        LOG.warn("no SMTP server configured");
        return;//from  w w  w.ja va  2  s  .c  o  m
    }
    String mailFrom = this.configuration.getValue(ConfigProperty.MAIL_FROM, String.class);
    if (null == mailFrom || mailFrom.trim().isEmpty()) {
        LOG.warn("no mail from address configured");
        return;
    }
    LOG.debug("mail from: " + mailFrom);

    Properties props = new Properties();
    props.put("mail.smtp.host", smtpServer);
    props.put("mail.from", mailFrom);

    String mailPrefix = this.configuration.getValue(ConfigProperty.MAIL_PREFIX, String.class);
    if (null != mailPrefix && false == mailPrefix.trim().isEmpty()) {
        subject = "[" + mailPrefix.trim() + "] " + subject;
    }

    Session session = Session.getInstance(props, null);
    try {
        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setFrom();
        mimeMessage.setRecipients(RecipientType.TO, mailTo);
        mimeMessage.setSubject(subject);
        mimeMessage.setSentDate(new Date());

        MimeBodyPart mimeBodyPart = new MimeBodyPart();
        mimeBodyPart.setText(messageBody);

        Multipart multipart = new MimeMultipart();
        // first part is body
        multipart.addBodyPart(mimeBodyPart);

        // second part is attachment
        if (null != attachment) {
            MimeBodyPart attachmentMimeBodyPart = new MimeBodyPart();
            DataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimetype);
            attachmentMimeBodyPart.setDataHandler(new DataHandler(dataSource));
            multipart.addBodyPart(attachmentMimeBodyPart);
        }

        mimeMessage.setContent(multipart);
        Transport.send(mimeMessage);
    } catch (MessagingException e) {
        throw new RuntimeException("send failed, exception: " + e.getMessage(), e);
    }
}

From source file:com.consol.citrus.demo.devoxx.service.MailService.java

/**
 * Send mail via SMTP connection.//from  w  w w  .  j a  v  a2 s  . c  o  m
 * @param to
 * @param subject
 * @param body
 */
public void sendMail(String to, String subject, String body) {
    Properties props = new Properties();
    props.put("mail.smtp.host", mailServerHost);
    props.put("mail.smtp.port", mailServerPort);
    props.put("mail.smtp.auth", true);

    Authenticator authenticator = new Authenticator() {
        private PasswordAuthentication pa = new PasswordAuthentication(username, password);

        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return pa;
        }
    };

    Session session = Session.getInstance(props, authenticator);
    session.setDebug(true);
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(new InternetAddress(from));
        InternetAddress[] address = { new InternetAddress(to) };
        message.setRecipients(Message.RecipientType.TO, address);
        message.setSubject(subject);
        message.setSentDate(new Date());
        message.setText(body);
        Transport.send(message);
    } catch (MessagingException e) {
        log.error("Failed to send mail!", e);
    }
}