Example usage for javax.mail Transport send

List of usage examples for javax.mail Transport send

Introduction

In this page you can find the example usage for javax.mail Transport send.

Prototype

public static void send(Message msg) throws MessagingException 

Source Link

Document

Send a message.

Usage

From source file:org.apache.hupa.server.InMemoryIMAPStoreCache.java

public void sendMessage(Message msg) throws MessagingException {
    Transport.send(msg);
}

From source file:br.com.cgcop.administrativo.modelo.ContaEmail.java

public void enviarEmailHtml(List<String> destinos, String msg, String titulo) {
    //       Recipient's email ID needs to be mentioned.
    String to = "";
    String rodape = "<br/><br/><br/><br/>  <div style=\"border-top: 1px dashed #c8cdbe;border-top: 1px dashed #c8cdbe \">"
            + "Esta mensagem  uma notificao enviada automaticamente por tanto no deve ser respondida. <br/> "
            + "<span style=\"font-style: italic; font-family: Narrow; font-size: large; color: rgb(0, 153, 0);\">Sistema de Gesto de Projetos e Obras - SGPO</span><br/>"
            + "<span style=\"font-size: large; font-style: italic; color: rgb(0, 153, 0); font-family: Narrow;\">Oiti Engenharia e Gesto Ambiental</span>"
            + "</div>";
    for (String d : destinos) {
        if (d.equals(destinos.get(destinos.size() - 1))) {
            to = to.concat(d);/*from  w w w  .  jav  a 2  s.  c o m*/
        } else {
            to = to.concat(d.concat(","));
        }
    }

    // Sender's email ID needs to be mentioned
    String from = this.email;
    final String username = this.email;//change accordingly
    final String password = this.senha;//change accordingly

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", this.host);
    props.put("mail.smtp.port", "25");

    // Get the Session object.
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    });

    try {

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

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

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

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

        // Send the actual HTML message, as big as you like
        message.setContent(msg + rodape, "text/html");

        // Send message
        Transport.send(message);

    } catch (MessagingException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:sk.lazyman.gizmo.web.app.PageEmail.java

private void sendPerformed(AjaxRequestTarget target) {
    try {/*from  w ww . j  av  a 2s .  c  o  m*/
        Properties props = System.getProperties();
        props.put("mail.smtp.host", getPropertyValue(MAIL_HOST));
        props.put("mail.smtp.port", getPropertyValue(MAIL_PORT));

        Session session = javax.mail.Session.getDefaultInstance(props, null);
        Message mail = buildMail(session);
        Transport.send(mail);

        boolean logged = logEmail(true, target);

        PageDashboard next = new PageDashboard();
        next.success(getString("Message.emailSuccess"));
        if (!logged) {
            next.warn(getString("Message.emailWasNotLogged"));
        }
        setResponsePage(next);
    } catch (Exception ex) {
        logEmail(false, target);
        handleGuiException(this, "Message.couldntSendEmail", ex, target);
    }
}

From source file:org.pentaho.platform.plugin.services.email.EmailService.java

/**
 * Tests the provided email configuration by sending a test email. This will just indicate that the server
 * configuration is correct and a test email was successfully sent. It does not test the destination address.
 * /*from ww w.j  a v  a 2  s.c o m*/
 * @param emailConfig
 *          the email configuration to test
 * @throws Exception
 *           indicates an error running the test (as in an invalid configuration)
 */
public String sendEmailTest(final IEmailConfiguration emailConfig) {
    final Properties emailProperties = new Properties();
    emailProperties.setProperty("mail.smtp.host", emailConfig.getSmtpHost());
    emailProperties.setProperty("mail.smtp.port", ObjectUtils.toString(emailConfig.getSmtpPort()));
    emailProperties.setProperty("mail.transport.protocol", emailConfig.getSmtpProtocol());
    emailProperties.setProperty("mail.smtp.starttls.enable", ObjectUtils.toString(emailConfig.isUseStartTls()));
    emailProperties.setProperty("mail.smtp.auth", ObjectUtils.toString(emailConfig.isAuthenticate()));
    emailProperties.setProperty("mail.smtp.ssl", ObjectUtils.toString(emailConfig.isUseSsl()));
    emailProperties.setProperty("mail.debug", ObjectUtils.toString(emailConfig.isDebug()));

    Session session = null;
    if (emailConfig.isAuthenticate()) {
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(emailConfig.getUserId(), emailConfig.getPassword());
            }
        };
        session = Session.getInstance(emailProperties, authenticator);
    } else {
        session = Session.getInstance(emailProperties);
    }

    String sendEmailMessage = "";
    try {
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(emailConfig.getDefaultFrom(), emailConfig.getFromName()));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailConfig.getDefaultFrom()));
        msg.setSubject(messages.getString("EmailService.SUBJECT"));
        msg.setText(messages.getString("EmailService.MESSAGE"));
        msg.setHeader("X-Mailer", "smtpsend");
        msg.setSentDate(new Date());
        Transport.send(msg);
        sendEmailMessage = "EmailTester.SUCESS";
    } catch (Exception e) {
        logger.error(messages.getString("EmailService.NOT_CONFIGURED"), e);
        sendEmailMessage = "EmailTester.FAIL";
    }
    return sendEmailMessage;
}

From source file:org.sofun.platform.notification.NotificationServiceImpl.java

@Override
public void sendEmail(Member member, Map<String, String> params) throws CoreException {

    final String emailsStr = params.get("emails");
    String[] emails = null;//  w w w.j  a  v a  2s . c  o  m
    if (emailsStr != null) {
        emails = params.get("emails").split(",");
    }

    String format = params.get("format");
    if (format == null) {
        format = "text/html";
    }
    Message message = new MimeMessage(mailer);

    final String encodingOptions = format + "; charset=UTF-8";
    try {
        message.setHeader("Content-Type", encodingOptions);

        String from = params.get("from");
        if (from == null || from.equals("")) {
            message.setFrom(new InternetAddress(CoreConstants.SOFUN_MAIL_FROM));
        } else {
            message.setFrom(new InternetAddress(from));
        }

        InternetAddress to[] = null;
        if (emails == null) {
            to = new InternetAddress[1];
            to[0] = new InternetAddress(member.getEmail());
        } else {
            to = new InternetAddress[emails.length];
            for (int i = 0; i < emails.length; i++) {
                to[i] = new InternetAddress(emails[i]);
            }
        }

        message.setRecipients(Message.RecipientType.TO, to);
        message.setSubject(params.get("subject"));

        String body = params.get("body");
        if (body != null) {
            body = body.replaceAll("(\\r|\\n)", "<p/>");
        }

        VelocityEngine ve = null;
        try {
            ve = getVelocityEngine();
        } catch (Exception e) {
            throw new CoreException(e.getMessage());
        }

        Template t = ve.getTemplate(params.get("templateId"));
        StringWriter writer = new StringWriter();

        VelocityContext context = new VelocityContext();

        // Add Member in velocity context.
        context.put("member", member);
        context.put("body", body);

        // Add all incoming params in velocity context.
        for (Map.Entry<String, String> entry : params.entrySet()) {
            context.put(entry.getKey(), entry.getValue());
        }

        t.merge(context, writer);

        message.setContent(writer.toString(), encodingOptions);
        Transport.send(message);
        String logEmails;
        if (emails != null) {
            logEmails = emailsStr;
        } else {
            logEmails = member.getEmail();
        }
        log.info("Sending an email to=" + logEmails);
    } catch (MessagingException e) {
        log.error("Failed to send an email. See error below.");
        throw new CoreException(e.getMessage());
    }

}

From source file:org.cern.flume.sink.mail.MailSink.java

@Override
public Status process() throws EventDeliveryException {
    Status status = null;/*  w  w  w .  j  av a2  s.  c  om*/

    // Start transaction
    Channel ch = getChannel();
    Transaction txn = ch.getTransaction();
    txn.begin();

    try {

        Event event = ch.take();

        if (event != null) {

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

            // Setup mail server
            properties.setProperty("mail.smtp.host", host);
            properties.put("mail.smtp.port", port);

            // Get the default Session object.
            Session session = Session.getDefaultInstance(properties);

            // Create a default MimeMessage object.
            MimeMessage mimeMessage = new MimeMessage(session);

            // Set From: header field of the header.
            mimeMessage.setFrom(new InternetAddress(sender));

            // Set To: header field of the header.
            for (String recipient : recipients) {
                mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
            }

            // Now set the subject and actual message
            Map<String, String> headers = event.getHeaders();

            String value;

            String mailSubject = subject;
            for (String field : subjectFields) {

                try {
                    if (field.equals("body")) {
                        value = new String(event.getBody());
                    } else {
                        value = new String(headers.get(field));
                    }
                } catch (NullPointerException t) {
                    value = "";
                }

                mailSubject = mailSubject.replace("%{" + field + "}", value);
            }

            String mailMessage = message;
            for (String field : messageFields) {

                try {
                    if (field.equals("body")) {
                        value = new String(event.getBody());
                    } else {
                        value = new String(headers.get(field));
                    }
                } catch (NullPointerException t) {
                    value = "";
                }

                mailMessage = mailMessage.replace("%{" + field + "}", value);
            }

            mimeMessage.setSubject(mailSubject);
            mimeMessage.setText(mailMessage);

            // Send message
            Transport.send(mimeMessage);

        }

        txn.commit();
        status = Status.READY;

    } catch (Throwable t) {

        txn.rollback();

        logger.error("Unable to send e-mail.", t);

        status = Status.BACKOFF;

        if (t instanceof Error) {
            throw (Error) t;
        }

    } finally {

        txn.close();

    }

    return status;
}

From source file:org.tizzit.util.mail.MailHelper.java

/**
 * Send an email in html-format in iso-8859-1-encoding
 * //from  ww  w . j av  a2  s  . co  m
 * @param subject the subject of the new mail
 * @param htmlMessage the content of the mail as html
 * @param alternativeTextMessage the content of the mail as text
 * @param from the sender-address
 * @param to the receiver-address
 * @param cc the address of the receiver of a copy of this mail
 * @param bcc the address of the receiver of a blind-copy of this mail
 */
public static void sendHtmlMail2(String subject, String htmlMessage, String alternativeTextMessage, String from,
        String to, String cc, String bcc) {
    try {
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));
        if (cc != null && !cc.equals(""))
            msg.setRecipients(Message.RecipientType.CC, cc);
        if (bcc != null && !bcc.equals(""))
            msg.setRecipients(Message.RecipientType.BCC, bcc);
        msg.addRecipients(Message.RecipientType.TO, to);
        msg.setSubject(subject, "ISO8859_1");
        msg.setSentDate(new Date());

        MimeMultipart multiPart = new MimeMultipart("alternative");
        MimeBodyPart htmlPart = new MimeBodyPart();
        MimeBodyPart textPart = new MimeBodyPart();

        textPart.setText(alternativeTextMessage, "ISO8859_1");
        textPart.setHeader("MIME-Version", "1.0");
        //textPart.setHeader("Content-Type", textPart.getContentType());
        textPart.setHeader("Content-Type", "text/plain;charset=\"ISO-8859-1\"");

        htmlPart.setContent(htmlMessage, "text/html;charset=\"ISO8859_1\"");
        htmlPart.setHeader("MIME-Version", "1.0");
        htmlPart.setHeader("Content-Type", "text/html;charset=\"ISO-8859-1\"");
        //htmlPart.setHeader("Content-Type", htmlPart.getContentType());

        multiPart.addBodyPart(textPart);
        multiPart.addBodyPart(htmlPart);

        multiPart.setSubType("alternative");

        msg.setContent(multiPart);
        msg.setHeader("MIME-Version", "1.0");
        msg.setHeader("Content-Type", multiPart.getContentType());

        Transport.send(msg);
    } catch (Exception e) {
        log.error("Error sending html-mail: " + e.getLocalizedMessage());
    }
}

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

public void sendOld() throws EmailException {
    LOG.info("init");
    try {//from www .  j av a  2  s.  c  o 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:it.infn.ct.security.actions.RegisterUser.java

private void sendMail(UserRequest usreq) throws MailException {
    javax.mail.Session session = null;//  ww  w  .  j  a  v a2s  . c  o m
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

    } catch (Exception ex) {
        log.error("Mail resource lookup error");
        log.error(ex.getMessage());
        throw new MailException("Mail Resource not available");
    }

    Message mailMsg = new MimeMessage(session);
    try {
        mailMsg.setFrom(new InternetAddress(mailFrom, idPAdmin));

        InternetAddress mailTo[] = new InternetAddress[1];
        mailTo[0] = new InternetAddress(usreq.getPreferredMail(),
                usreq.getTitle() + " " + usreq.getGivenname() + " " + usreq.getSurname());
        mailMsg.setRecipients(Message.RecipientType.TO, mailTo);

        String ccMail[] = mailCC.split(";");
        InternetAddress mailCCopy[] = new InternetAddress[ccMail.length];
        for (int i = 0; i < ccMail.length; i++) {
            mailCCopy[i] = new InternetAddress(ccMail[i]);
        }

        mailMsg.setRecipients(Message.RecipientType.CC, mailCCopy);

        mailMsg.setSubject(mailSubject);

        mailBody = mailBody.replaceAll("_USER_",
                usreq.getTitle() + " " + usreq.getGivenname() + " " + usreq.getSurname());

        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

    } catch (UnsupportedEncodingException ex) {
        log.error(ex);
        throw new MailException("Mail from address format not valid");
    } catch (MessagingException ex) {
        log.error(ex);
        throw new MailException("Mail message has problems");
    }

}

From source file:Implement.DAO.CommonDAOImpl.java

@Override
public boolean sendMail(String title, String receiver, String messageContent) throws MessagingException {
    final String username = "registration@youtripper.com";
    final String password = "Tripregister190515";
    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "mail.youtripper.com");

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }/* ww w  .  j av a  2  s. c o  m*/
    });

    Message message = new MimeMessage(session);
    message.setFrom(new InternetAddress("registration@youtripper.com"));
    message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));
    message.setSubject(title);
    message.setContent(messageContent, "text/html; charset=utf-8");
    Transport.send(message);
    return true;

}