Example usage for javax.mail.internet MimeMessage addRecipient

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

Introduction

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

Prototype

public void addRecipient(RecipientType type, Address address) throws MessagingException 

Source Link

Document

Add this recipient address to the existing ones of the given type.

Usage

From source file:egovframework.oe1.cms.cmm.notify.email.service.impl.EgovOe1SSLMailServiceImpl.java

protected void send(String subject, String content, String contentType) throws Exception {
    Properties props = new Properties();

    props.put("mail.transport.protocol", "smtps");
    props.put("mail.smtps.host", getHost());
    props.put("mail.smtps.auth", "true");

    Session mailSession = Session.getDefaultInstance(props);
    mailSession.setDebug(false);//from   ww w. j  a va  2  s. co m
    Transport transport = mailSession.getTransport();

    MimeMessage message = new MimeMessage(mailSession);
    message.setFrom(new InternetAddress("www.egovframe.org", "webmaster", "euc-kr"));
    message.setSubject(subject);

    MimeBodyPart mbp1 = new MimeBodyPart();
    mbp1.setText(content, "utf-8");

    Multipart mp = new MimeMultipart();
    mp.addBodyPart(mbp1);

    List<String> fileNames = getAtchFileIds();

    for (Iterator<String> it = fileNames.iterator(); it.hasNext();) {
        MimeBodyPart mbp2 = new MimeBodyPart();

        // attach the file to the message
        FileDataSource fds = new FileDataSource(it.next());
        mbp2.setDataHandler(new DataHandler(fds));

        mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr", "B")); // Q : ascii, B : 

        mp.addBodyPart(mbp2);
    }

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

    for (Iterator<String> it = getReceivers().iterator(); it.hasNext();)
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(it.next()));

    transport.connect(getHost(), getPort(), getUsername(), getPassword());
    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
    transport.close();
}

From source file:nc.noumea.mairie.appock.services.impl.MailServiceImpl.java

@Override
public Message sendMail(AppockMail appockMail) throws MessagingException {

    if (CollectionUtils.isEmpty(appockMail.getListeDestinataire())) {
        log.warn("Mail non envoy, liste des destinataires vide : " + appockMail);
        return null;
    }//from   w  w w .  j  a  v  a  2  s.  c o m

    MimeMessage msg = new MimeMessage(mailServer);
    msg.setFrom(appockMail.getFrom() != null ? appockMail.getFrom() : defaultFrom());

    String prefixeSujet = isModeProduction() ? "" : "[TEST APPOCK] ";
    msg.setSubject(prefixeSujet + appockMail.getSujet(), configService.getEncodageSujetEmail());

    StringBuilder infoAdditionnelle = new StringBuilder();

    for (InternetAddress adresse : appockMail.getListeDestinataire()) {
        if (isModeProduction()) {
            // on est en production, envoi rel de mail au destinataire
            msg.addRecipient(Message.RecipientType.TO, adresse);
        } else {
            // en test, on envoie le mail  la personne connecte
            InternetAddress adresseTesteur = getAdresseMailDestinataireTesteur();
            if (adresseTesteur != null) {
                msg.addRecipient(Message.RecipientType.TO, adresseTesteur);
            }
            List<String> listeAdresseMail = new ArrayList<>();
            for (InternetAddress internetAddress : appockMail.getListeDestinataire()) {
                listeAdresseMail.add(internetAddress.getAddress());
            }
            infoAdditionnelle.append("En production cet email serait envoy vers ")
                    .append(StringUtils.join(listeAdresseMail, ", ")).append("<br/><hr/>");
            break;
        }
    }

    String contenuFinal = "";
    if (!StringUtils.isBlank(infoAdditionnelle.toString())) {
        contenuFinal += "<font face=\"arial\" >" + infoAdditionnelle.toString() + "</font>";
    }

    contenuFinal += "<font face=\"arial\" >" + appockMail.getContenu() + "<br/><br/></font>"
            + configService.getPiedDeMail();

    gereBonLivraisonDansMail(appockMail, msg, contenuFinal);

    if (!ArrayUtils.isEmpty(msg.getAllRecipients())) {
        Transport.send(msg);
    }

    return msg;
}

From source file:org.j2free.email.EmailService.java

private void send(InternetAddress from, InternetAddress[] recipients, String subject, String body,
        ContentType contentType, Priority priority, boolean ccSender)
        throws AddressException, MessagingException, RejectedExecutionException {
    MimeMessage message = new MimeMessage(session);
    message.setFrom(from);/*from  ww  w. ja v a2s  .com*/
    message.setRecipients(Message.RecipientType.TO, recipients);

    for (Map.Entry<String, String> header : headers.entrySet())
        message.setHeader(header.getKey(), header.getValue());

    // CC the sender if they want
    if (ccSender)
        message.addRecipient(Message.RecipientType.CC, from);

    message.setReplyTo(new InternetAddress[] { from });

    message.setSubject(subject);
    message.setSentDate(new Date());

    if (contentType == ContentType.PLAIN) {
        // Just set the body as plain text
        message.setText(body, "UTF-8");
    } else {
        MimeMultipart multipart = new MimeMultipart("alternative");

        // Create the text part
        MimeBodyPart text = new MimeBodyPart();
        text.setText(new HtmlFilter().filterForEmail(body), "UTF-8");

        // Add the text part
        multipart.addBodyPart(text);

        // Create the HTML portion
        MimeBodyPart html = new MimeBodyPart();
        html.setContent(body, ContentType.HTML.toString());

        // Add the HTML portion
        multipart.addBodyPart(html);

        // set the message content
        message.setContent(multipart);
    }
    enqueue(message, priority);
}

From source file:org.eurekaclinical.user.service.email.FreeMarkerEmailSender.java

/**
 * Send an email to the given email address with the given subject line,
 * using contents generated from the given template and parameters.
 *
 * @param templateName The name of the template used to generate the
 * contents of the email.//w  ww. ja  v  a  2 s  .com
 * @param subject The subject for the email being sent.
 * @param emailAddress Sends the email to this address.
 * @param params The template is merged with these parameters to generate
 * the content of the email.
 * @throws EmailException Thrown if there are any errors in generating
 * content from the template, composing the email, or sending the email.
 */
private void sendMessage(final String templateName, final String subject, final String emailAddress,
        final Map<String, Object> params) throws EmailException {
    Writer stringWriter = new StringWriter();
    try {
        Template template = this.configuration.getTemplate(templateName);
        template.process(params, stringWriter);
    } catch (TemplateException | IOException e) {
        throw new EmailException(e);
    }

    String content = stringWriter.toString();
    MimeMessage message = new MimeMessage(this.session);
    try {
        InternetAddress fromEmailAddress = null;
        String fromEmailAddressStr = this.userServiceProperties.getFromEmailAddress();
        if (fromEmailAddressStr != null) {
            fromEmailAddress = new InternetAddress(fromEmailAddressStr);
        }
        if (fromEmailAddress == null) {
            fromEmailAddress = InternetAddress.getLocalAddress(this.session);
        }
        if (fromEmailAddress == null) {
            try {
                fromEmailAddress = new InternetAddress(
                        "no-reply@" + InetAddress.getLocalHost().getCanonicalHostName());
            } catch (UnknownHostException ex) {
                fromEmailAddress = new InternetAddress("no-reply@localhost");
            }
        }
        message.setFrom(fromEmailAddress);
        message.setSubject(subject);
        message.setContent(content, "text/plain");
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailAddress));
        message.setSender(fromEmailAddress);
        Transport.send(message);
    } catch (MessagingException e) {
        LOGGER.error("Error sending the following email message:");
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            message.writeTo(out);
            out.close();
        } catch (IOException | MessagingException ex) {
            try {
                out.close();
            } catch (IOException ignore) {
            }
        }
        LOGGER.error(out.toString());
        throw new EmailException(e);
    }
}

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./*from  w  w  w . j  av  a2s . c  om*/
 *
 * @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.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;// w w w. jav  a2s .  c o  m
    }

    // 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:org.openbizview.util.Bvt002.java

/**
* Enva notificacin a usuario al cambiar la contrasea
**///from  w  ww  .j a  v a 2 s  .c  o m
private void ChangePassNotification2(String mail, String clave) {
    try {
        Context initContext = new InitialContext();
        Session session = (Session) initContext.lookup(JNDIMAIL);
        // Crear el mensaje a enviar
        MimeMessage mm = new MimeMessage(session);
        // Establecer las direcciones a las que ser enviado
        // el mensaje (test2@gmail.com y test3@gmail.com en copia
        // oculta)
        // mm.setFrom(new
        // InternetAddress("opennomina@dvconsultores.com"));
        mm.addRecipient(Message.RecipientType.TO, new InternetAddress(mail));

        // Establecer el contenido del mensaje
        mm.setSubject(getMessage("mailUserUserChgPass"));
        mm.setText(getMessage("mailNewUserMsj2"));

        // use this is if you want to send html based message
        mm.setContent(getMessage("mailNewUserMsj6") + " " + coduser.toUpperCase() + " / " + clave
                + "<br/><br/> " + getMessage("mailNewUserMsj2"), "text/html; charset=utf-8");

        // Enviar el correo electrnico
        Transport.send(mm);
        //System.out.println("Correo enviado exitosamente");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.github.dougkelly88.FLIMPlateReaderGUI.SequencingClasses.GUIComponents.XYSequencing.java

public void sendEmail(String subject, String text, String toEmail) {

    // Recipient's email ID needs to be mentioned.
    String to = toEmail;/*from w  w  w.j  a v  a  2 s .  c  o m*/

    // Sender's email ID needs to be mentioned
    String from = "flimplatereader@gmail.com";

    // Assuming you are sending email from localhost
    String host = "localhost";

    // Get system properties
    //  Properties properties = System.getProperties();
    Properties properties = System.getProperties();

    // Setup mail server
    //properties.setProperty("mail.smtp.host", "10.101.3.229");
    properties.setProperty("mail.smtp.host", "smtp.gmail.com");
    properties.put("mail.smtp.port", "587");
    properties.setProperty("mail.user", "flimplatereader");
    properties.setProperty("mail.password", "flimimages");
    properties.put("mail.smtp.starttls.enable", "true");
    properties.put("mail.smtp.auth", "true"); //enable authentication

    final String pww = "flimimages";
    Session session;
    session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() {
        protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
            return new javax.mail.PasswordAuthentication("flimplatereader@gmail.com", pww);
        }
    });

    try {
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // Set Subject: header field
        message.setSubject(subject);

        // Now set the actual message
        message.setText(text);

        // Send message
        Transport.send(message);
        System.out.println("Sent message successfully....");
    } catch (MessagingException mex) {
        mex.printStackTrace();
    }
}

From source file:com.fullmetalgalaxy.server.pm.PMServlet.java

@Override
protected void doPost(HttpServletRequest p_request, HttpServletResponse p_response)
        throws ServletException, IOException {
    ServletFileUpload upload = new ServletFileUpload();
    try {//from  ww  w .  ja  v  a2  s.c  om
        // build message to send
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        MimeMessage msg = new MimeMessage(session);
        msg.setSubject("[FMG] no subject", "text/plain");
        msg.setSender(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin"));
        msg.setFrom(new InternetAddress("admin@fullmetalgalaxy.com", "FMG Admin"));
        EbAccount fromAccount = null;

        // Parse the request
        FileItemIterator iter = upload.getItemIterator(p_request);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                if ("msg".equalsIgnoreCase(item.getFieldName())) {
                    msg.setContent(Streams.asString(item.openStream(), "UTF-8"), "text/plain");
                }
                if ("subject".equalsIgnoreCase(item.getFieldName())) {
                    msg.setSubject("[FMG] " + Streams.asString(item.openStream(), "UTF-8"), "text/plain");
                }
                if ("toid".equalsIgnoreCase(item.getFieldName())) {
                    EbAccount account = null;
                    try {
                        account = FmgDataStore.dao().get(EbAccount.class,
                                Long.parseLong(Streams.asString(item.openStream(), "UTF-8")));
                    } catch (NumberFormatException e) {
                    }
                    if (account != null) {
                        msg.addRecipient(Message.RecipientType.TO,
                                new InternetAddress(account.getEmail(), account.getPseudo()));
                    }
                }
                if ("fromid".equalsIgnoreCase(item.getFieldName())) {
                    try {
                        fromAccount = FmgDataStore.dao().get(EbAccount.class,
                                Long.parseLong(Streams.asString(item.openStream(), "UTF-8")));
                    } catch (NumberFormatException e) {
                    }
                    if (fromAccount != null) {
                        if (fromAccount.getAuthProvider() == AuthProvider.Google
                                && !fromAccount.isHideEmailToPlayer()) {
                            msg.setFrom(new InternetAddress(fromAccount.getEmail(), fromAccount.getPseudo()));
                        } else {
                            msg.setFrom(
                                    new InternetAddress(fromAccount.getFmgEmail(), fromAccount.getPseudo()));
                        }
                    }
                }
            }
        }

        // msg.addRecipients( Message.RecipientType.BCC, InternetAddress.parse(
        // "archive@fullmetalgalaxy.com" ) );
        Transport.send(msg);

    } catch (Exception e) {
        log.error(e);
        p_response.sendRedirect("/genericmsg.jsp?title=Error&text=" + e.getMessage());
        return;
    }

    p_response.sendRedirect("/genericmsg.jsp?title=Message envoye");
}

From source file:org.enlacerh.util.FileUploadController.java

/**
 * Mtodo que enva los recibos de pago a cada usuario
 * @throws IOException //from   w  ww . j a v  a 2 s  .com
 * @throws NumberFormatException 
 * **/
public void enviarRP(String to, String laruta, String file) throws NumberFormatException, IOException {
    try {
        //System.out.println("Enviando recibo");
        //System.out.println(jndimail());
        Context initContext = new InitialContext();
        Session session = (Session) initContext.lookup(jndimail());
        // Crear el mensaje a enviar
        MimeMessage mm = new MimeMessage(session);

        // Establecer las direcciones a las que ser enviado
        // el mensaje (test2@gmail.com y test3@gmail.com en copia
        // oculta)
        // mm.setFrom(new
        // InternetAddress("opennomina@dvconsultores.com"));
        mm.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

        // Establecer el contenido del mensaje
        mm.setSubject(getMessage("mailRP"));
        //mm.setText(getMessage("mailContent"));

        // Create the message part 
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        messageBodyPart.setContent(getMessage("mailRPcontent"), "text/html; charset=utf-8");

        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = laruta + File.separator + file + ".pdf";
        javax.activation.DataSource source = new FileDataSource(filename);
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(file + ".pdf");
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        mm.setContent(multipart);

        // Enviar el correo electrnico
        Transport.send(mm);
        //System.out.println("Correo enviado exitosamente a :" + to);
        //System.out.println("Fin recibo");
    } catch (Exception e) {
        msj = new FacesMessage(FacesMessage.SEVERITY_FATAL, e.getMessage() + ": " + to, "");
        FacesContext.getCurrentInstance().addMessage(null, msj);
        e.printStackTrace();
    }
}