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:com.intranet.intr.proveedores.EmpControllerGestion.java

public void enviarProvUC(proveedores proveedor) {
    String cuerpo = "";
    String servidorSMTP = "smtp.1and1.es";
    String puertoEnvio = "465";
    Properties props = new Properties();//propiedades a agragar
    props.put("mail.smtp.user", miCorreo);//correo origen
    props.put("mail.smtp.host", servidorSMTP);//tipo de servidor
    props.put("mail.smtp.port", puertoEnvio);//puesto de salida
    props.put("mail.smtp.starttls.enable", "true");//inicializar el servidor
    props.put("mail.smtp.auth", "true");//autentificacion
    props.put("mail.smtp.password", "angel2010");//autentificacion
    props.put("mail.smtp.socketFactory.port", puertoEnvio);//activar el puerto
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.socketFactory.fallback", "false");

    SecurityManager security = System.getSecurityManager();

    Authenticator auth = new autentificadorSMTP();//autentificar el correo
    Session session = Session.getInstance(props, auth);//se inica una session
    // session.setDebug(true);

    try {//from ww  w .ja  v  a 2 s . c om
        // Creamos un objeto mensaje tipo MimeMessage por defecto.
        MimeMessage mensajeE = new MimeMessage(session);

        // Asignamos el de o from? al header del correo.
        mensajeE.setFrom(new InternetAddress(miCorreo));

        // Asignamos el para o to? al header del correo.
        mensajeE.addRecipient(Message.RecipientType.TO, new InternetAddress(proveedor.getEmail()));

        // Asignamos el asunto
        mensajeE.setSubject("Su Perfil Personal");

        // Creamos un cuerpo del correo con ayuda de la clase BodyPart
        //BodyPart cuerpoMensaje = new MimeBodyPart();

        // Asignamos el texto del correo
        String text = "Acceda con usuario: " + proveedor.getUsuario() + " y contrasea: "
                + proveedor.getContrasenna()
                + ", al siguiente link http://decorakia.ddns.net/Intranet/login.htm";
        // Asignamos el texto del correo
        cuerpo = "<!DOCTYPE html><html>" + "<head> " + "<title></title>" + "</head>" + "<body>"
                + "<img src='http://decorakia.ddns.net/unnamed.png'>" + "<p>" + text + "</p>" + "</body>"
                + "</html>";
        mensajeE.setContent("<!DOCTYPE html>" + "<html>" + "<head> " + "<title></title>" + "</head>" + "<body>"
                + "<img src='http://decorakia.ddns.net/unnamed.png'>" + "<p>" + text + "</p>" + "</body>"
                + "</html>", "text/html");
        //mensaje.setText(text);

        // Creamos un multipart al correo

        // Enviamos el correo
        Transport.send(mensajeE);
        System.out.println("Mensaje enviado");

    } catch (MessagingException e) {
        e.printStackTrace();
    }
}

From source file:org.apache.axis2.transport.mail.EMailSender.java

public void send() throws AxisFault {

    try {//  w  w  w. ja  v  a  2  s .  c o m

        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return passwordAuthentication;
            }
        });
        MimeMessage msg = new MimeMessage(session);

        // Set date - required by rfc2822
        msg.setSentDate(new java.util.Date());

        // Set from - required by rfc2822
        String from = properties.getProperty("mail.smtp.from");
        if (from != null) {
            msg.setFrom(new InternetAddress(from));
        }

        EndpointReference epr = null;
        MailToInfo mailToInfo;

        if (messageContext.getTo() != null && !messageContext.getTo().hasAnonymousAddress()) {
            epr = messageContext.getTo();
        }

        if (epr != null) {
            if (!epr.hasNoneAddress()) {
                mailToInfo = new MailToInfo(epr);
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress()));

            } else {
                if (from != null) {
                    mailToInfo = new MailToInfo(from);
                    msg.addRecipient(Message.RecipientType.TO,
                            new InternetAddress(mailToInfo.getEmailAddress()));
                } else {
                    String error = EMailSender.class.getName() + "Couldn't countinue due to"
                            + " FROM addressing is NULL";
                    log.error(error);
                    throw new AxisFault(error);
                }
            }
        } else {
            // replyto : from : or reply-path;
            if (from != null) {
                mailToInfo = new MailToInfo(from);
                msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailToInfo.getEmailAddress()));
            } else {
                String error = EMailSender.class.getName() + "Couldn't countinue due to"
                        + " FROM addressing is NULL and EPR is NULL";
                log.error(error);
                throw new AxisFault(error);
            }

        }

        msg.setSubject("__ Axis2/Java Mail Message __");

        if (mailToInfo.isxServicePath()) {
            msg.setHeader(Constants.X_SERVICE_PATH, "\"" + mailToInfo.getContentDescription() + "\"");
        }

        if (inReplyTo != null) {
            msg.setHeader(Constants.IN_REPLY_TO, inReplyTo);
        }

        createMailMimeMessage(msg, mailToInfo, format);
        Transport.send(msg);

        log.info("Message being send. [Action = ]" + messageContext.getOptions().getAction());

        sendReceive(messageContext, msg.getMessageID());
    } catch (AddressException e) {
        throw new AxisFault(e.getMessage(), e);
    } catch (MessagingException e) {
        throw new AxisFault(e.getMessage(), e);
    }
}

From source file:org.nuxeo.ecm.user.invite.UserInvitationComponent.java

protected void generateMail(String destination, String copy, String title, String content)
        throws NamingException, MessagingException {

    InitialContext ic = new InitialContext();
    Session session = (Session) ic.lookup(getJavaMailJndiName());

    MimeMessage msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(session.getProperty("mail.from")));
    msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(destination, false));
    if (!isBlank(copy)) {
        msg.addRecipient(Message.RecipientType.CC, new InternetAddress(copy, false));
    }//  w  ww. j  av a  2  s  . co m

    msg.setSubject(title, "UTF-8");
    msg.setSentDate(new Date());
    msg.setContent(content, "text/html; charset=utf-8");

    Transport.send(msg);
}

From source file:org.igov.io.mail.Mail.java

public void sendOld() throws EmailException {
    LOG.info("init");
    try {//ww  w  . j a v a  2  s.co  m
        MultiPartEmail oMultiPartEmail = new MultiPartEmail();
        LOG.info("(getHost()={})", getHost());
        oMultiPartEmail.setHostName(getHost());

        String[] asTo = { sMailOnly(getTo()) };
        if (getTo().contains("\\,")) {
            asTo = getTo().split("\\,");//sTo
            for (String s : asTo) {
                LOG.info("oMultiPartEmail.addTo (s={})", s);
                oMultiPartEmail.addTo(s, "receiver");
            }
        }

        LOG.info("(getFrom()={})", getFrom());
        LOG_BIG.debug("(getFrom()={})", getFrom());
        oMultiPartEmail.setFrom(getFrom(), getFrom());//"iGov"
        oMultiPartEmail.setSubject(getHead());
        LOG.info("getHead()={}", getHead());
        String sLogin = getAuthUser();
        if (sLogin != null && !"".equals(sLogin.trim())) {
            oMultiPartEmail.setAuthentication(sLogin, getAuthPassword());
            LOG.info("withAuth");
        } else {
            LOG.info("withoutAuth");
        }
        //oMultiPartEmail.setAuthentication(getAuthUser(), getAuthPassword());
        LOG.info("(getAuthUser()={})", getAuthUser());
        //LOG.info("getAuthPassword()=" + getAuthPassword());
        oMultiPartEmail.setSmtpPort(getPort());
        LOG.info("(getPort()={})", getPort());
        oMultiPartEmail.setSSL(isSSL());
        LOG.info("(isSSL()={})", isSSL());
        oMultiPartEmail.setTLS(isTLS());
        LOG.info("(isTLS()={})", isTLS());

        oSession = oMultiPartEmail.getMailSession();
        MimeMessage oMimeMessage = new MimeMessage(oSession);

        //oMimeMessage.setFrom(new InternetAddress(getFrom(), "iGov", DEFAULT_ENCODING));
        oMimeMessage.setFrom(new InternetAddress(getFrom(), getFrom()));
        //oMimeMessage.addRecipient(Message.RecipientType.CC, new InternetAddress(sTo, sToName, DEFAULT_ENCODING));
        String sReceiverName = "receiver";
        if (asTo.length == 1) {
            sReceiverName = getToName();
        }
        for (String s : asTo) {
            LOG.info("oMimeMessage.addRecipient (s={})", s);
            //oMultiPartEmail.addTo(s, "receiver");
            oMimeMessage.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(s, sReceiverName, DEFAULT_ENCODING));
        }

        //oMimeMessage.addRecipient(Message.RecipientType.TO,
        //        new InternetAddress(sTo, "recipient", DEFAULT_ENCODING));
        //new InternetAddress(getTo(), "recipient", DEFAULT_ENCODING));
        oMimeMessage.setSubject(getHead(), DEFAULT_ENCODING);

        _AttachBody(getBody());
        //LOG.info("(getBody()={})", getBody());
        oMimeMessage.setContent(oMultiparts);

        //            oMimeMessage.getRecipients(Message.RecipientType.CC);
        //methodCallRunner.registrateMethod(Transport.class.getName(), "send", new Object[]{oMimeMessage});
        Transport.send(oMimeMessage);
        LOG.info("Send " + getTo() + "!!!!!!!!!!!!!!!!!!!!!!!!");
    } catch (Exception oException) {
        LOG.error("FAIL: {} (getTo()={})", oException.getMessage(), getTo());
        LOG.trace("FAIL:", oException);
        throw new EmailException("Error happened when sending email (" + getTo() + ")" + "Exception message: "
                + oException.getMessage(), oException);
    }
    LOG.info("SUCCESS: Sent!");
}

From source file:org.opencastproject.messages.MailService.java

/** Message -> MimeMessage. */
private MimeMessage toMimeMessage(Mail mail) throws Exception {
    final MimeMessage msg = smtpService.createMessage();
    for (EmailAddress reply : mail.getReplyTo())
        msg.setReplyTo(new Address[] { new InternetAddress(reply.getAddress(), reply.getName(), "UTF-8") });

    // recipient// ww w.j a va2  s  .  co  m
    for (EmailAddress recipient : mail.getRecipients()) {
        msg.addRecipient(javax.mail.Message.RecipientType.TO,
                new InternetAddress(recipient.getAddress(), recipient.getName(), "UTF-8"));
    }

    // subject
    msg.setSubject(mail.getSubject());

    EmailAddress from = mail.getSender();
    msg.setFrom(new InternetAddress(from.getAddress(), from.getName(), "UTF-8"));
    // body
    msg.setText(mail.getBody(), "UTF-8");
    return msg;
}

From source file:cz.incad.vdkcommon.solr.Indexer.java

private void sendDemandMail(SolrDocument resultDoc, String id) {
    try {//w ww .ja va  2s.com
        String title = (String) resultDoc.getFieldValues("title").toArray()[0];
        String pop = (String) resultDoc.getFieldValue("poptavka_ext");
        JSONObject j = new JSONObject(pop);

        String from = opts.getString("admin.email");
        Knihovna kn = new Knihovna(j.getString("knihovna"));
        String to = kn.getEmail();
        String zaznam = j.optString("zaznam");
        String code = j.optString("code");
        String exemplar = j.optString("exemplar");
        try {
            Properties properties = System.getProperties();
            Session session = Session.getDefaultInstance(properties);

            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            message.setSubject(opts.getString("admin.email.demand.subject"));

            String link = opts.getString("app.url") + "/original?id=" + id;
            String body = opts.getString("admin.email.demand.body").replace("${demand.title}", title)
                    .replace("${demand.url}", link);
            message.setText(body);

            Transport.send(message);
            LOGGER.fine("Sent message successfully....");
        } catch (MessagingException ex) {
            LOGGER.log(Level.SEVERE, "Error sending email to: {0}, from {1} ", new Object[] { to, from });
            LOGGER.log(Level.SEVERE, null, ex);
        }
    } catch (NamingException | SQLException ex) {
        LOGGER.log(Level.SEVERE, null, ex);
    }
}

From source file:com.mylab.mail.OpenCmsMailService.java

public void addRecipientsWhitelist(MimeMessage message, String to_address, String to_name,
        GreetingcardConfig greetingcardConfig) throws UnsupportedEncodingException, MessagingException {
    WhitelistDao whitelistDao = new JdbcWhitelistDao(greetingcardConfig);
    List<String> receivers = new ArrayList<String>();

    if ((to_address != null) && to_address.contains("@"))
        receivers.add(to_address);//from  ww w. ja va 2s . com
    else
        try {
            receivers = whitelistDao.getReceiverlist(to_name);
        } catch (DataAccessException e) {
        }

    Iterator<String> itr = receivers.iterator();
    String receiverAddress;
    String receiverName = null;
    while (itr.hasNext()) {
        receiverAddress = itr.next();
        try {
            receiverName = whitelistDao.getReceiverName(receiverAddress);
        } catch (DataAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(receiverAddress, receiverName));
    }
}

From source file:jp.co.acroquest.endosnipe.collector.notification.smtp.SMTPSender.java

/**
 * ??/*from w w  w.  j a v a2s  .c o  m*/
 * 
 * @param config javelin.properties???
 * @param entry ??
 * @return ???
 * @throws MessagingException ??????
 */
protected MimeMessage createMailMessage(final DataCollectorConfig config, final AlarmEntry entry)
        throws MessagingException {
    // JavaMail???
    Properties props = System.getProperties();
    String smtpServer = this.config_.getSmtpServer();
    if (smtpServer == null || smtpServer.length() == 0) {
        LOGGER.log(LogMessageCodes.SMTP_SERVER_NOT_SPECIFIED);
        String detailMessageKey = "collector.notification.smtp.SMTPSender.SMTPNotSpecified";
        String messageDetail = CommunicatorMessages.getMessage(detailMessageKey);

        throw new MessagingException(messageDetail);
    }
    props.setProperty(SMTP_HOST_KEY, smtpServer);
    int smtpPort = config.getSmtpPort();
    props.setProperty(SMTP_PORT_KEY, String.valueOf(smtpPort));

    // ???????
    Session session = null;
    if (authenticator_ == null) {
        // ?????
        session = Session.getDefaultInstance(props);
    } else {
        // ???
        props.setProperty(SMTP_AUTH_KEY, "true");
        session = Session.getDefaultInstance(props, authenticator_);
    }

    // MIME??
    MimeMessage message = new MimeMessage(session);

    // ??
    // :
    Date date = new Date();
    String encoding = this.config_.getSmtpEncoding();
    message.setHeader("X-Mailer", X_MAILER);
    message.setHeader("Content-Type", "text/plain; charset=\"" + encoding + "\"");
    message.setSentDate(date);

    // :from
    String from = this.config_.getSmtpFrom();
    InternetAddress fromAddr = new InternetAddress(from);
    message.setFrom(fromAddr);

    // :to
    String[] recipients = this.config_.getSmtpTo().split(",");
    for (String toStr : recipients) {
        InternetAddress toAddr = new InternetAddress(toStr);
        message.addRecipient(Message.RecipientType.TO, toAddr);
    }

    // :body, subject
    String subject;
    String body;
    subject = createSubject(entry, date);
    try {
        body = createBody(entry, date);
    } catch (IOException ex) {
        LOGGER.log(LogMessageCodes.FAIL_READ_MAIL_TEMPLATE, "");
        body = createDefaultBody(entry, date);
    }

    message.setSubject(subject, encoding);
    message.setText(body, encoding);

    return message;
}

From source file:trendplot.TrendPlot.java

private void testEmail() {
    Properties fMailServerConfig;
    fMailServerConfig = new Properties();
    fMailServerConfig.setProperty("mail.host", "ldas-cit.ligo.caltech.edu");
    fMailServerConfig.setProperty("mail.smtp.host", "ldas-cit.ligo.caltech.edu");

    Session session = Session.getDefaultInstance(fMailServerConfig, null);
    MimeMessage message = new MimeMessage(session);
    try {/*from   w ww .  j av a 2 s  .c o m*/
        //the "from" address may be set in code, or set in the
        //config file under "mail.from" ; here, the latter style is used
        message.setFrom(new InternetAddress("areeda@ligo.caltech.edu"));
        String email = "joe@areeda.com";

        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
        String msg = "<h3>this is a test</h3>";
        message.setSubject("Test email");
        message.setText(msg, "utf-8", "html");
        Transport.send(message);
        System.out.format("Email sent to %1$s\n", email);
    } catch (MessagingException ex) {
        System.err.format("Exception: %1$s: %2$s", ex.getClass().getSimpleName(), ex.getLocalizedMessage());
    }

}

From source file:trendplot.TrendPlot.java

private void emailResults() throws IOException, WebUtilException {
    emailStart = System.currentTimeMillis();

    ViewerConfig vc = new ViewerConfig();
    if (!config.isEmpty()) {
        vc.setConfigFileName(config);/*  w w w.  j a  v a 2s .  c  o m*/
    }
    vc.readConfig();
    String host = vc.get("webserver");
    if (host == null || host.isEmpty()) {
        host = "ldvw.ligo.caltech.edu";
    }
    String servlet = vc.get("servlet");
    if (servlet == null || servlet.isEmpty()) {
        servlet = "ldvw/view";
    }
    PageItemList msg = new PageItemList();

    if (!imgIds.isEmpty()) {
        msg.add(new PageItemHeader("The following results are available:", 3));
        PageTable tbl = new PageTable();
        for (int img = 0; img < imgIds.size(); img++) {
            PageTableRow row = new PageTableRow();
            row.add(descriptions.get(img));
            Integer imgId = imgIds.get(img);
            String url = "https://" + host + "/" + servlet + "?act=getimg&amp;imgId=" + imgId.toString();
            PageItemTextLink link = new PageItemTextLink(url, "link");
            row.add(link);
            tbl.addRow(row);
        }
        msg.add(tbl);
        msg.addBlankLines(2);

        String groupIntro = String.format("These images have also been added to the %1$s group.<br>", group);
        msg.add(new PageItemString(groupIntro, false));
        String groupUrl = String.format(
                "https://%1$s/%2$s?act=imagehistory&amp;group=%3$s" + "&amp;usrSel=%4$s", host, servlet, group,
                user);
        PageItemTextLink groupLink = new PageItemTextLink(groupUrl, "Click for image group page.");
        msg.add(groupLink);
        msg.addBlankLines(2);
    } else if (!checkOnly) {
        msg.add("Sorry but no images were produced.");
        msg.addBlankLines(2);
    }
    if (verbose || imgIds.isEmpty()) {
        msg.add(new PageItemString("<br>Stdout:<br><br>", false));
        String outText = outStringWriter.toString().replace("\n", "<br>\n");
        msg.add(new PageItemString(outText, false));

        msg.add(new PageItemString("<br>Stderr:<br><br>", false));
        outText = errStringWriter.toString().replace("\n", "<br>\n");
        msg.add(new PageItemString(outText, false));
    }
    msg.add(new PageItemString("<br><br>Sincerly,<br>The LigoDV-web group", false));

    Float condor = (startTime - qtime) / 1000.f;
    String condorTime = qtime == 0 ? "?" : String.format("%1$.2f", condor);
    Float overhead = (transferStart - startTime) / 1000.f;
    Float xfer = (plotStart - transferStart) / 1000.f;
    Float plot = (emailStart - plotStart) / 1000.f;
    String timing = String.format(
            "Timing: queue: %1$s, overhead: %2$.2f, data collection: %3$.2f, " + "plot: %4$.2f seconds",
            condorTime, overhead, xfer, plot);
    outPrintWriter.println(timing);
    msg.addBlankLines(2);
    msg.add(new PageItemString(timing, false));
    msg.addBlankLines(1);

    String msgText = msg.getHtml();

    Properties fMailServerConfig;
    fMailServerConfig = new Properties();
    fMailServerConfig.setProperty("mail.host", "ldas-cit.ligo.caltech.edu");
    fMailServerConfig.setProperty("mail.smtp.host", "ldas-cit.ligo.caltech.edu");

    Session session = Session.getDefaultInstance(fMailServerConfig, null);
    MimeMessage message = new MimeMessage(session);
    try {
        //the "from" address may be set in code, or set in the
        //config file under "mail.from" ; here, the latter style is used
        message.setFrom(new InternetAddress("areeda@ligo.caltech.edu"));

        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));

        message.setSubject("Trend plot results are available.");
        message.setText(msgText, "utf-8", "html");
        Transport.send(message);
        outPrintWriter.format("Email sent to %1$s\n", email);
        errPrintWriter.println("Email message:");
        errPrintWriter.println(msgText);
    } catch (MessagingException ex) {
        throw new WebUtilException("Cannot send email. " + ex);
    }
}