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:com.commoncoupon.mail.EmailProcessor.java

public Integer call() throws Exception {
    MimeMessage message = new MimeMessage(getSession());

    try {/*from w  w  w  . j  a  v a 2  s .  c o  m*/
        if (from != null && (from != null && from.trim() != "")) {
            InternetAddress sentFrom = new InternetAddress(from);
            message.setFrom(sentFrom);
            if (log.isDebugEnabled())
                log.debug("Email sent from: " + sentFrom);
        }

        if (to != null && to.length > 0) {
            InternetAddress[] sendTo = new InternetAddress[to.length];
            for (int i = 0; i < to.length; i++) {
                sendTo[i] = new InternetAddress((String) to[i]);
                if (log.isDebugEnabled())
                    log.debug("Sending e-mail to: " + to[i]);
            }
            message.setRecipients(Message.RecipientType.TO, sendTo);
        }

        if (cc != null && cc.length > 0) {
            InternetAddress[] copyTo = new InternetAddress[cc.length];
            for (int i = 0; i < cc.length; i++) {
                copyTo[i] = new InternetAddress((String) cc[i]);
                if (log.isDebugEnabled())
                    log.debug("Copying e-mail to: " + cc[i]);
            }
            message.setRecipients(Message.RecipientType.CC, copyTo);
        }
        message.setSentDate(new Date());
        message.setSubject(subject);
        message.setContent(content, mimeType);
        Transport.send(message);
    } catch (Exception e) {
        log.error("Failed to send email.", e);
        return (1);
    }

    return (0);
}

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

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

    Session session = getSession();// w w w. j  a va2 s . com
    final MimeMessage mimeMessage = new MimeMessage(session);
    try {
        mimeMessage.setFrom(new InternetAddress(config.getFrom(), config.getFromName()));
        addRecipientsWhitelist(mimeMessage, config.getTo(), config.getToName(), config.getCardconfig());
    } 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);
}

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

public void sendMessage(String to, String subject, String content, String soapAction)
        throws MessagingException {
    log.info("SENDING message from " + from + " to " + to);

    MimeMessage msg = new MimeMessage(session);

    msg.setHeader("transport.mail.soapaction", soapAction);
    msg.addRecipients(Message.RecipientType.TO, to);
    msg.setSubject(subject);/*  w  ww. ja  v a 2  s .  com*/
    msg.setText(content);
    Transport.send(msg);
}

From source file:Sender2.java

/**
 * Send the file with no filename, assuming you've already called the
 * setBody() method.//from w  ww .  j av a 2  s .c  om
 */
public void sendFile() {
    try {

        // Finally, send the message! (use static Transport method)
        Transport.send(mesg);

    } catch (MessagingException ex) {
        while ((ex = (MessagingException) ex.getNextException()) != null) {
            ex.printStackTrace();
        }
    }
}

From source file:Security.EmailSender.java

/**
 * Metda sendUerAuthEmail sli na generovanie a zaslanie potvrdzovacieho emailu, ktor sli na overenie zadanho emailu pouvatea, novo registrovanmu pouvateovi.
 * @param email - emailov adresa pouvatea, ktormu bude zalan email
 * @param userToken - jedine?n 32 znakov identifiktor registrcie pouvatea
 * @param firstName - krstn meno pouvatea
 * @param lastName - priezvisko pouvatea
 *///from   w  w w  .j ava  2 s .  c  o  m
public void sendUserAuthEmail(String email, String userToken, String firstName, String lastName) {
    String name = "NONE";
    String surname = "NONE";
    if (firstName != null) {
        name = firstName;
    }
    if (lastName != null) {
        surname = lastName;
    }

    Properties props = new Properties();
    props.put("mail.smtp.host", server);
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("skuska.api.3@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject("Confirmation email from GPSWebApp server!!!");
        //message.setText(userToken);
        message.setSubject("Confirmation email from GPSWebApp server!!!");
        if (system.startsWith("Windows")) {
            message.setContent("<html><head><meta charset=\"Windows-1250\"></head><body><h1>Hello " + name + " "
                    + surname
                    + ", please confirm your email by clicking on link ...</h1><a href=http://localhost:8084/GPSWebApp/TryToAcceptUser.jsp?token="
                    + userToken + "&email=" + email + ">LINK</a></body></html>", "text/html");
        } else {
            message.setContent("<html><head><meta charset=\"Windows-1250\"></head><body><h1>Hello " + name + " "
                    + surname
                    + ", please confirm your email by clicking on link ...</h1><a href=http://gps.kpi.fei.tuke.sk/TryToAcceptUser.jsp?token="
                    + userToken + "&email=" + email + ">LINK</a></body></html>", "text/html");
        }

        Transport.send(message);

        FileLogger.getInstance().createNewLog("Successfuly sent email to user " + email + ".");

    } catch (MessagingException e) {
        FileLogger.getInstance().createNewLog("ERROR: cannot sent email to user " + email + ".");
    }

}

From source file:sk.mlp.security.EmailSender.java

/**
 * Metda sendUerAuthEmail sli na generovanie a zaslanie potvrdzovacieho emailu, ktor sli na overenie zadanho emailu pouvatea, novo registrovanmu pouvateovi.
 * @param email - emailov adresa pouvatea, ktormu bude zalan email
 * @param userToken - jedine?n 32 znakov identifiktor registrcie pouvatea
 * @param firstName - krstn meno pouvatea
 * @param lastName - priezvisko pouvatea
 *///  w  w w.  j  a  va 2s .  c o  m
public void sendUserAuthEmail(String email, String userToken, String firstName, String lastName) {
    String name = "NONE";
    String surname = "NONE";
    if (firstName != null) {
        name = firstName;
    }
    if (lastName != null) {
        surname = lastName;
    }

    Properties props = new Properties();
    props.put("mail.smtp.host", server);
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");

    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(userName, password);
        }
    });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("skuska.api.3@gmail.com"));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email));
        message.setSubject("Confirmation email from gTraxxx app!!!");
        //message.setText(userToken);
        message.setSubject("Confirmation email from gTraxxx app!!!");
        if (system.startsWith("Windows")) {
            message.setContent("<html><head><meta charset=\"Windows-1250\"></head><body><h1>Hello " + name + " "
                    + surname
                    + ", please confirm your email by clicking on link ...</h1><a href=http://localhost:8080/gTraxxx/TryToAcceptUser.jsp?token="
                    + userToken + "&email=" + email + ">LINK</a></body></html>", "text/html");
        } else {
            message.setContent("<html><head><meta charset=\"Windows-1250\"></head><body><h1>Hello " + name + " "
                    + surname
                    + ", please confirm your email by clicking on link ...</h1><a href=http://gps.kpi.fei.tuke.sk/TryToAcceptUser.jsp?token="
                    + userToken + "&email=" + email + ">LINK</a></body></html>", "text/html");
        }

        Transport.send(message);

        FileLogger.getInstance().createNewLog("Successfuly sent email to user " + email + ".");

    } catch (MessagingException e) {
        FileLogger.getInstance().createNewLog("ERROR: cannot sent email to user " + email + ".");
    }

}

From source file:de.hska.ld.core.service.impl.MailServiceImpl.java

@Override
public void sendMail(String fullName, String email, String templateFileName, Map<String, Object> model) {
    ;//from w ww. j  av  a2 s  . c o m
    if (Boolean.parseBoolean(env.getProperty("email.enabled"))) {
        Locale locale = LocaleContextHolder.getLocale();
        ResourceBundle bundle = ResourceBundle.getBundle("messages", locale);
        model.put("dear", bundle.getString("email.dear"));
        model.put("fullName", fullName);
        model.put("greeting", bundle.getString("email.greeting"));

        String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine,
                "templates/mail/" + templateFileName, "UTF-8", model);

        Properties properties = getMailProperties();

        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(MAIL_PROPERTIES.getProperty("email.username"),
                        MAIL_PROPERTIES.getProperty("email.password"));
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(MAIL_PROPERTIES.getProperty("email.from.system"));
            helper.setTo(email);
            helper.setSubject(model.containsKey("subject") ? (String) model.get("subject") : "");
            helper.setText(text, true);
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.redhat.rhn.common.messaging.SmtpMail.java

/** {@inheritDoc} */
public void send() {

    try {/*from www. ja  v  a2  s.c  o m*/
        Address[] addrs = message.getRecipients(RecipientType.TO);
        if (addrs == null || addrs.length == 0) {
            log.warn("Aborting mail message " + message.getSubject() + ": No recipients");
            return;
        }
        Transport.send(message);
    } catch (MessagingException me) {
        String msg = "MessagingException while trying to send email: " + me.toString();
        log.warn(msg);
        throw new JavaMailException(msg, me);
    }
}

From source file:frameworkcontentspeed.Utils.SendEmailAtachament.java

public static void SendEmailSephoraPassed(String adresaSephora, String from, String grupTestContent,
        String grupSephora, String subject, String filename) throws FileNotFoundException, IOException {

    //Get properties object    
    Properties props = new Properties();
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.socketFactory.port", "465");
    props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.port", "465");
    //get Session   
    Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(from, "anda.cristea");
        }/*from w w w.j  a  v  a2  s .  co  m*/
    });
    //compose message    
    try {
        MimeMessage message = new MimeMessage(session);
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(grupTestContent));
        message.addRecipient(Message.RecipientType.BCC, new InternetAddress(grupSephora));

        message.setSubject(subject);
        // message.setText(msg);

        BodyPart messageBodyPart = new MimeBodyPart();

        messageBodyPart.setText("Raport teste automate");

        Multipart multipart = new MimeMultipart();

        multipart.addBodyPart(messageBodyPart);

        messageBodyPart = new MimeBodyPart();

        DataSource source = new FileDataSource(filename);

        messageBodyPart.setDataHandler(new DataHandler(source));

        messageBodyPart.setFileName(filename);

        multipart.addBodyPart(messageBodyPart);

        message.setContent(multipart);

        //send message  
        Transport.send(message);
        //  System.out.println("message sent successfully");
    } catch (Exception ex) {
        System.out.println("eroare trimitere email-uri");
        System.out.println(ex.getMessage());

    }

}

From source file:org.squale.squalecommon.util.mail.javamail.JavaMailProviderImpl.java

/**
 * This method send mail//from  w  w w.ja v a  2  s. c o  m
 * 
 * @param sender Sender Address
 * @param recipients List of recipient address
 * @param subject Subject of the mail
 * @param content Content of the mail
 * @throws MailException Exception happened the send of the mail
 */
public void sendMail(String sender, String[] recipients, String subject, String content) throws MailException {

    // Initialization of the mail provider
    init();

    // if there is mail configuration information
    if (smtpServer != null && (senderAddress != null || sender != null)) {

        // Properties used for sending mails
        Properties props = System.getProperties();
        props.put("mail.smtp.host", smtpServer);

        Session session = smtpAuthent(props);

        // Header message definition
        MimeMessage message = new MimeMessage(session);
        try {
            // If a sender argument is not null we use it
            if (sender != null) {
                message.setFrom(new InternetAddress(sender));
            }
            // If the sender argument is null
            else {
                message.setFrom(new InternetAddress(senderAddress));
            }

            // We send to each recipient
            for (int i = 0; i <= recipients.length - 1; i++) {
                String mailAddress = (String) recipients[i];
                LOG.debug("Recipent : " + recipients[i]);
                message.addRecipient(Message.RecipientType.BCC, new InternetAddress(mailAddress));
            }

            // Body message definition
            message.setSubject(subject);
            message.setText(content, "iso-8859-1");

            // Send of the mail
            Transport.send(message);

        } catch (AddressException e) {
            throw new MailException(e);
        } catch (MessagingException e) {
            throw new MailException(e);
        }
    } else {
        String message = MailMessages.getString("mail.exception.noConfig");
        throw new MailException(message);
    }

}