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:rapture.mail.Mailer.java

public static void email(String[] recipients, String subject, String message) throws MessagingException {
    final SMTPConfig config = getSMTPConfig();
    Session session = getSession(config);
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(config.getFrom()));
    InternetAddress[] address = new InternetAddress[recipients.length];
    for (int i = 0; i < recipients.length; i++)
        address[i] = new InternetAddress(recipients[i]);
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject(subject);//from ww w. j  av  a  2  s .c om
    msg.setContent(message, MediaType.PLAIN_TEXT_UTF_8.toString());
    msg.setSentDate(new Date());
    Transport.send(msg);
}

From source file:EmailJndiServlet.java

private void sendMessage(String to, String from, String subject, String bodyContent) throws Exception {

    Message mailMsg = null;//from   ww  w. j av  a 2s. com

    synchronized (mailSession) {

        mailMsg = new MimeMessage(mailSession);//a new email message
    }

    InternetAddress[] addresses = null;

    try {

        if (to != null) {

            //throws 'AddressException' if the 'to' email address
            //violates RFC822 syntax
            addresses = InternetAddress.parse(to, false);

            mailMsg.setRecipients(Message.RecipientType.TO, addresses);

        } else {

            throw new MessagingException("The mail message requires a 'To' address.");

        }

        if (from != null)
            mailMsg.setFrom(new InternetAddress(from));

        if (subject != null)
            mailMsg.setSubject(subject);

        if (bodyContent != null)
            mailMsg.setText(bodyContent);

        //Finally, send the mail message; throws a 'SendFailedException' 
        //if any of the message's recipients have an invalid adress
        Transport.send(mailMsg);

    } catch (Exception exc) {

        throw exc;
    }
}

From source file:mb.MbTermin.java

private void posaljiMail(Student student, Profesor profesorId, Termin t) {

    //ToDo change username and password for google account
    final String username = "*****";
    final String password = "*****";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");

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

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(profesorId.getEmail()));
        message.setSubject("Konsultacije");
        message.setText("Potovani " + profesorId.getIme() + " " + profesorId.getPrezime() + ","
                + "\n\n Student " + student.getIme() + " " + student.getPrezime()
                + " je zakazao termin konsultacija" + " za datum " + t.getTerminPK().getVreme() + ".");
        Transport.send(message);

        System.out.println("Message sent");
    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.trivago.mail.pigeon.mail.MailFacade.java

public void sendMail(MailTransport mailTransport) {
    log.debug("Mail delivery started");
    File propertyfile = ((PropertiesConfiguration) Settings.create().getConfiguration()).getFile();
    Properties config = new Properties();

    try {/*ww w  . jav  a 2 s  .co m*/
        config.load(new FileReader(propertyfile));
    } catch (IOException e) {
        log.error(e);
    }

    Session session = Session.getDefaultInstance(config);

    log.debug("Received session");

    MimeMessage message = new MimeMessage(session);

    String to = mailTransport.getTo();
    String from = mailTransport.getFrom();
    String replyTo = mailTransport.getReplyTo();
    String subject = mailTransport.getSubject();
    String html = mailTransport.getHtml();
    String text = mailTransport.getText();

    try {
        Address fromAdr = new InternetAddress(from);
        Address toAdr = new InternetAddress(to);
        Address rplyAdr = new InternetAddress(replyTo);

        message.setSubject(subject);
        message.setFrom(fromAdr);
        message.setRecipient(Message.RecipientType.TO, toAdr);
        message.setReplyTo(new Address[] { rplyAdr });
        message.setSender(fromAdr);
        message.addHeader("Return-path", replyTo);
        message.addHeader("X-TRV-MID", mailTransport.getmId());
        message.addHeader("X-TRV-UID", mailTransport.getuId());

        // Content
        MimeBodyPart messageTextPart = new MimeBodyPart();
        messageTextPart.setText(text);
        messageTextPart.setContent(html, "text/html");

        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(messageTextPart);

        // Put parts in message
        message.setContent(multipart);

        log.debug("Dispatching message");
        Transport.send(message);
        log.debug("Mail delivery ended");
    } catch (MessagingException e) {
        log.error(e);
    }

}

From source file:org.mot.common.tools.EmailFactory.java

public void sendEmail(String recipient, String subject, String body) {

    if (enabled) {

        try {//www  . jav a2s .  c o  m

            if (recipient == null || recipient == "") {
                recipient = rcpt;
            }

            // 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.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

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

            // Send the actual HTML message, as big as you like
            message.setText(body);

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

    }

}

From source file:org.intermine.util.MailUtils.java

/**
 * Send an email to an address, supplying the recipient, subject and body.
 *
 * @param to the address to send to//from w  w w.  j  a  v  a 2 s.  c o  m
 * @param subject The Subject of the email
 * @param body The content of the email
 * @param from the address to send from
 * @param webProperties Common properties for all emails (such as from, authentication)
 * @throws MessagingException if there is a problem creating the email
 */
public static void email(String to, String subject, String body, String from, final Properties webProperties)
        throws MessagingException {
    final String user = webProperties.getProperty("mail.smtp.user");
    String smtpPort = webProperties.getProperty("mail.smtp.port");
    String authFlag = webProperties.getProperty("mail.smtp.auth");
    String starttlsFlag = webProperties.getProperty("mail.smtp.starttls.enable");

    Properties properties = System.getProperties();

    properties.put("mail.smtp.host", webProperties.get("mail.host"));
    properties.put("mail.smtp.user", user);
    // Fix to "javax.mail.MessagingException: 501 Syntactically
    // invalid HELO argument(s)" problem
    // See http://forum.java.sun.com/thread.jspa?threadID=487000&messageID=2280968
    properties.put("mail.smtp.localhost", "localhost");
    if (smtpPort != null) {
        properties.put("mail.smtp.port", smtpPort);
    }
    if (starttlsFlag != null) {
        properties.put("mail.smtp.starttls.enable", starttlsFlag);
    }
    if (authFlag != null) {
        properties.put("mail.smtp.auth", authFlag);
    }

    Session session;
    if (authFlag != null && ("true".equals(authFlag) || "t".equals(authFlag))) {
        Authenticator authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                String password = (String) webProperties.get("mail.server.password");
                return new PasswordAuthentication(user, password);
            }
        };
        session = Session.getInstance(properties, authenticator);
    } else {
        session = Session.getInstance(properties);
    }
    MimeMessage message = new MimeMessage(session);
    if (StringUtils.isEmpty(user)) {
        message.setFrom(new InternetAddress(from));
    } else {
        message.setReplyTo(InternetAddress.parse(from, true));
        message.setFrom(new InternetAddress(user));
    }
    message.addRecipient(Message.RecipientType.TO, InternetAddress.parse(to, true)[0]);
    message.setSubject(subject);
    message.setContent(body, "text/plain");
    Transport.send(message);
}

From source file:com.spartasystems.holdmail.smtp.OutgoingMailSender.java

protected void sendMessage(Message message) throws MessagingException {
    Transport.send(message);
}

From source file:org.wf.dp.dniprorada.util.Mail.java

@Override
public void send() throws EmailException {

    try {/*from  ww  w . ja v  a 2  s .  c  om*/
        log.info("init");
        MultiPartEmail oMultiPartEmail = new MultiPartEmail();
        oMultiPartEmail.setHostName(getHost());
        log.info("getHost()=" + getHost());
        oMultiPartEmail.addTo(getTo(), "receiver");
        log.info("getTo()=" + getTo());
        oMultiPartEmail.setFrom(getFrom(), getFrom());//"iGov"
        log.info("getFrom()=" + getFrom());
        oMultiPartEmail.setSubject(getHead());
        log.info("getHead()=" + getHead());

        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));
        oMimeMessage.addRecipient(Message.RecipientType.TO,
                new InternetAddress(getTo(), "recipient", DEFAULT_ENCODING));

        oMimeMessage.setSubject(getHead(), DEFAULT_ENCODING);

        _Attach(getBody());

        oMimeMessage.setContent(oMultiparts);

        //            oMimeMessage.getRecipients(Message.RecipientType.CC);
        Transport.send(oMimeMessage);
        log.info("[send]:Transport.send!");
    } catch (Exception exc) {
        log.error("[send]", exc);
        throw new EmailException("Error happened when sending email", exc);
    }
}

From source file:com.app.mail.DefaultMailSender.java

@Override
public void sendContactMessage(String emailAddress, String message) throws Exception {

    Session session = _authenticateOutboundEmailAddress();

    Message emailMessage = _populateContactMessage(emailAddress, message, session);

    Transport.send(emailMessage);
}

From source file:fr.xebia.cocktail.MailService.java

public void sendCocktail(Cocktail cocktail, String recipient, String cocktailPageUrl)
        throws MessagingException {

    Message msg = new MimeMessage(mailSession);

    msg.setFrom(fromAddress);//w  ww. j  ava  2  s .c om
    msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

    msg.setSubject("[Cocktail] " + cocktail.getName());
    String message = cocktail.getName() + "\n" //
            + "--------------------\n" //
            + "\n" //
            + Strings.nullToEmpty(cocktail.getInstructions()) + "\n" //
            + "\n" //
            + cocktailPageUrl;
    msg.setContent(message, "text/plain");

    Transport.send(msg);
    auditLogger.info("Sent to {} cocktail '{}'", recipient, cocktail.getName());
    sentEmailCounter.incrementAndGet();
}