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.usergrid.apm.service.util.Mailer.java

public static void send(String recipeintEmail, String subject, String messageText) {
    /*//from  ww w.  jav  a  2  s .c o m
     * It is a good practice to put this in a java.util.Properties file and
     * encrypt password. Scroll down to comments below to see how to use
     * java.util.Properties in JSF context.
     */
    Properties props = new Properties();
    try {
        props.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("conf/email.properties"));
    } catch (IOException e) {
        e.printStackTrace();
    }

    final String senderEmail = props.getProperty("mail.smtp.sender.email");
    final String smtpUser = props.getProperty("mail.smtp.user");
    final String senderName = props.getProperty("mail.smtp.sender.name");
    final String senderPassword = props.getProperty("senderPassword");
    final String emailtoCC = props.getProperty("instaopsOpsEmailtoCC");

    Session session = Session.getDefaultInstance(props, new Authenticator() {
        @Override
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(smtpUser, senderPassword);
        }
    });
    session.setDebug(false);

    try {
        MimeMessage message = new MimeMessage(session);

        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setContent(messageText, "text/html");

        // Add message text
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);
        message.setSubject(subject);
        InternetAddress senderAddress = new InternetAddress(senderEmail, senderName);
        message.setFrom(senderAddress);
        message.addRecipient(Message.RecipientType.CC, new InternetAddress(emailtoCC));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipeintEmail));
        Transport.send(message);
        log.info("email sent");
    } catch (MessagingException m) {
        log.error(m.toString());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

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

/**
 * Send mail via SMTP connection.//from   www  . j  a v a 2  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);
    }
}

From source file:uk.ac.ox.it.ords.api.project.services.impl.SendMailTLS.java

protected void sendMail(String subject, String messageText) throws Exception {

    ////from www.ja  v  a 2s. c  o m
    // Validate Mail server settings
    //
    if (!props.containsKey("mail.smtp.username") || !props.containsKey("mail.smtp.password")
            || !props.containsKey("mail.smtp.host")) {
        log.error("Unable to send emails as email server configuration is missing");
        throw new Exception("Unable to send emails as email server configuration is missing");
    }

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(props.get("mail.smtp.username").toString(),
                    props.get("mail.smtp.password").toString());
        }
    });

    try {
        Message message = new MimeMessage(session);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject(subject);
        message.setText(messageText);

        Transport.send(message);

        if (log.isDebugEnabled()) {
            log.debug(String.format("Sent email to %s", email));
            log.debug("with content: " + messageText);
        }
    } catch (MessagingException e) {
        log.error("Unable to send email to " + email, e);
        throw new Exception("Unable to send email to " + email, e);
    }
}

From source file:org.infoglue.cms.util.mail.MailService.java

/**
 * //from   w w w  .  j a  va 2s  .  c om
 */
public void send(final Message message) throws SystemException {
    try {
        Transport.send(message);
    } catch (MessagingException e) {
        e.printStackTrace();
        throw new SystemException("Unable to send message.", e);
    }

}

From source file:uk.ac.ox.it.ords.api.database.services.impl.SendMailTLS.java

protected void sendMail(String subject, String messageText) throws Exception {

    ////ww  w .  j a  v  a2s.  c  om
    // Validate Mail server settings
    //
    if (!props.containsKey("mail.smtp.username") || !props.containsKey("mail.smtp.password")
            || !props.containsKey("mail.smtp.host")) {
        log.error("Unable to send emails as email server configuration is missing");
        //throw new Exception("Unable to send emails as email server configuration is missing");
        return; // 
    }

    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(props.get("mail.smtp.username").toString(),
                    props.get("mail.smtp.password").toString());
        }
    });

    try {
        Message message = new MimeMessage(session);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject(subject);
        message.setText(messageText);

        Transport.send(message);

        if (log.isDebugEnabled()) {
            log.debug(String.format("Sent email to %s", email));
            log.debug("with content: " + messageText);
        }
    } catch (MessagingException e) {
        log.error("Unable to send email to " + email, e);
        throw new Exception("Unable to send email to " + email, e);
    }
}

From source file:net.kamhon.ieagle.function.email.SendMail.java

public void send(String to, String cc, String bcc, String from, String subject, String text, String emailType) {

    // Session session = Session.getInstance(props, null);
    Session session = Session.getInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(emailServerSetting.getUsername(),
                    emailServerSetting.getPassword());
        }//from  ww w  .j ava2 s . c o m
    });

    session.setDebug(emailServerSetting.isDebug());

    try {
        Message msg = new MimeMessage(session);
        if (StringUtils.isNotBlank(from)) {
            msg.setFrom(new InternetAddress(from));
        } else {
            msg.setFrom();
        }

        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        if (StringUtils.isNotBlank(cc)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if (StringUtils.isNotBlank(bcc)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        msg.setSubject(subject);
        if (Emailq.TYPE_HTML.equalsIgnoreCase(emailType)) {
            msg.setContent(text, "text/html");
        } else {
            msg.setText(text);
        }
        msg.setSentDate(new java.util.Date());
        Transport.send(msg);
    } catch (MessagingException mex) {
        mex.printStackTrace();
        Exception ex = null;
        if ((ex = mex.getNextException()) != null) {
            ex.printStackTrace();
        }
        throw new SystemErrorException(mex);
    }
}

From source file:org.nekorp.workflow.desktop.servicio.imp.ServicioAlertaEmailImp.java

@Override
public void enviarAlerta(List<AlertaServicio> alertas) {
    try {/*ww  w. ja  v  a2 s  . c o  m*/
        for (AlertaServicio x : alertas) {
            Message message = new MimeMessage(template.buildSession());
            message.setFrom(new InternetAddress(template.getMailSender()));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(template.getMailRecipient()));
            message.setSubject("Alerta");
            ST contenido = new ST(contenidoRaw);
            contenido.add("cliente", x.getNombreCliente());
            contenido.add("tipo", x.getTipoAuto());
            contenido.add("marca", x.getMarcaAuto());
            contenido.add("placas", x.getPlacasAuto());
            contenido.add("kilometraje", x.getKilometrajeAuto());
            contenido.add("servicio", x.getDescripcionServicio());
            contenido.add("kilometrajeServicio", x.getKilometrajeServicio());
            message.setText(contenido.render());
            Transport.send(message);
        }
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:ips1ap101.ejb.core.mail.MailerBean.java

@Override
public Message sendMessage(String addressList, String subject, String text) throws MessagingException {
    if (EA.isMailingEnabled()) {
    } else {/*from   w  ww.  jav a  2  s .  com*/
        return null;
    }
    if (StringUtils.isBlank(addressList)) {
        throw new InvalidParameterException("addressList");
    }
    if (StringUtils.isBlank(subject)) {
        throw new InvalidParameterException("subject");
    }
    if (StringUtils.isBlank(text)) {
        throw new InvalidParameterException("text");
    }
    Address[] internetAddressList = InternetAddress.parse(addressList, false);
    Date timeStamp = new Date();
    Message message = new MimeMessage(session);
    message.setFrom();
    message.setHeader("X-Mailer", "JavaMail");
    message.setRecipients(Message.RecipientType.TO, internetAddressList);
    message.setSentDate(timeStamp);
    message.setSubject(subject);
    message.setText(text);
    Transport.send(message);
    return message;
}

From source file:org.overlord.sramp.governance.services.NotificationResourceTest.java

@Test
public void testMail() {
    try {/*  w  w  w  .j  av  a  2 s . co  m*/
        mailServer = SimpleSmtpServer.start(smtpPort);
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.host", "localhost"); //$NON-NLS-1$ //$NON-NLS-2$
        properties.setProperty("mail.smtp.port", String.valueOf(smtpPort)); //$NON-NLS-1$
        Session mailSession = Session.getDefaultInstance(properties);
        MimeMessage m = new MimeMessage(mailSession);
        Address from = new InternetAddress("me@gmail.com"); //$NON-NLS-1$
        Address[] to = new InternetAddress[1];
        to[0] = new InternetAddress("dev@mailinator.com"); //$NON-NLS-1$
        m.setFrom(from);
        m.setRecipients(Message.RecipientType.TO, to);
        m.setSubject("test"); //$NON-NLS-1$
        m.setContent("test", "text/plain"); //$NON-NLS-1$ //$NON-NLS-2$
        Transport.send(m);

        Assert.assertTrue(mailServer.getReceivedEmailSize() > 0);
        @SuppressWarnings("rawtypes")
        Iterator iter = mailServer.getReceivedEmail();
        while (iter.hasNext()) {
            SmtpMessage email = (SmtpMessage) iter.next();
            System.out.println(email.getBody());
            Assert.assertEquals("test", email.getBody()); //$NON-NLS-1$
        }

    } catch (AddressException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        mailServer.stop();
    }

}

From source file:com.synyx.greetingcard.mail.OpenCmsMailService.java

public void sendMail(MessageConfig config) throws MessagingException {
    log.debug("Sending message " + config);

    Session session = getSession();/* w w w  .j a v a2s  . c  om*/
    final MimeMessage mimeMessage = new MimeMessage(session);
    try {
        mimeMessage.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        mimeMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(config.getTo(), config.getToName()));
    } catch (UnsupportedEncodingException ex) {
        throw new MessagingException("Setting from or to failed", ex);
    }
    mimeMessage.setSubject(config.getSubject());
    mimeMessage.setContent(config.getContent(), config.getContentType());
    // we don't send in a new Thread so that we get the Exception
    Transport.send(mimeMessage);
}