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.hiperium.bo.manager.mail.EmailMessageManager.java

/**
 * Sends an email with the new user password.
 * //  ww w. j a  v a  2 s  .c  o  m
 * @param user
 * @throws javax.mail.internet.AddressException
 * @throws javax.mail.MessagingException
 */
public void sendNewPassword(User user) {
    try {
        this.log.debug("sendNewPassword() - START");
        // Create the corresponding user locale.
        Locale locale = null;
        if (StringUtils.isBlank(user.getLanguageId())) {
            locale = Locale.getDefault();
        } else {
            locale = new Locale(user.getLanguageId());
        }
        ResourceBundle resource = ResourceBundle.getBundle(EnumI18N.COMMON.value(), locale);

        // Get system properties
        Properties properties = System.getProperties();
        // Setup mail server
        properties.setProperty("mail.smtp.host", CloudEmailUser.HOST);
        properties.setProperty("mail.user", CloudEmailUser.USERNAME);
        properties.setProperty("mail.password", CloudEmailUser.PASSWORD);
        // Get the default Session object.
        Session session = Session.getDefaultInstance(properties);
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);
        // Set From: header field of the header.
        message.setFrom(new InternetAddress(CloudEmailUser.ADDRESS));
        // Set To: header field of the header.
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(user.getEmail()));
        // Set Subject: header field
        message.setSubject(resource.getString(GENERATED_USER_PASSWD_SUBJECT));
        // Send the actual HTML message, as big as you like
        message.setContent(MessageFormat.format(resource.getString(GENERATED_USER_PASSWD_CONTENT),
                user.getFirstname(), user.getLastname(), user.getPassword()), "text/html");
        // Send message
        Transport.send(message);
        this.log.debug("sendNewPassword() - END");
    } catch (AddressException e) {
        this.log.error("AddressException to send email to " + user.getEmail(), e);
    } catch (MessagingException e) {
        this.log.error("MessagingException to send email to " + user.getEmail(), e);
    }
}

From source file:org.geoserver.wps.mail.SendMail.java

/**
 * Send an EMail to a specified address.
 * /*w  w w  .j  a  v  a  2 s .co m*/
 * @param address the to address
 * @param subject the email address
 * @param body message to send
 * @throws MessagingException the messaging exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void send(String address, String subject, String body) {
    try {
        // Session session = Session.getDefaultInstance(props, null);
        Session session = Session.getDefaultInstance(props,
                (conf.getMailSmtpAuth().equalsIgnoreCase("true") ? new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(conf.getUserName(), conf.getPassword());
                    }
                } : null));

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(conf.getFromAddress(), conf.getFromAddressname()));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address));
        message.setSubject(subject);
        message.setText(body.toString());

        Transport.send(message);

    } catch (Exception e) {
        if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, e.getLocalizedMessage(), e);
        }
    }

}

From source file:com.jwm123.loggly.reporter.ReportMailer.java

public void send() throws MessagingException {
    if (StringUtils.isNotBlank(config.getMailServer()) && recipients.length > 0) {
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.port", config.getMailPort().toString());
        props.setProperty("mail.smtp.host", config.getMailServer());
        if (StringUtils.isNotBlank(config.getMailUsername())
                && StringUtils.isNotBlank(config.getMailPassword())) {
            props.setProperty("mail.smtp.user", config.getMailUsername());
            props.setProperty("mail.smtp.password", config.getMailPassword());
        }//from  w ww.jav  a2 s.c  om

        Session session = Session.getDefaultInstance(props);

        MimeMessage message = new MimeMessage(session);
        message.addFrom(new Address[] { new InternetAddress(config.getMailFrom()) });
        message.setSubject(subject);
        for (String recipient : recipients) {
            message.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }

        MimeMultipart containingMultipart = new MimeMultipart("mixed");

        MimeMultipart messageMultipart = new MimeMultipart("alternative");
        containingMultipart.addBodyPart(newMultipartBodyPart(messageMultipart));

        messageMultipart.addBodyPart(newTextBodyPart(getText()));

        MimeMultipart htmlMultipart = new MimeMultipart("related");
        htmlMultipart.addBodyPart(newHtmlBodyPart(getHtml()));
        messageMultipart.addBodyPart(newMultipartBodyPart(htmlMultipart));

        containingMultipart.addBodyPart(addReportAttachment());

        message.setContent(containingMultipart);

        Transport.send(message);
    }
}

From source file:org.modelibra.util.Emailer.java

/**
 * Sends an email./*from  w w w .  ja  v  a2s. com*/
 * 
 * @throws dmLite
 *             exception if there is a problem
 */
public void send() throws ModelibraException {
    try {
        MimeMessage message = new MimeMessage(emailSession);
        InternetAddress fromIA = new InternetAddress(from);
        message.setFrom(fromIA);
        InternetAddress toIA = new InternetAddress(to);
        message.addRecipient(Message.RecipientType.TO, toIA);
        message.setSubject(subject);
        message.setText(content);
        emailStore.connect(outServer, code, password);
        Transport.send(message);
        emailStore.close();
    } catch (MessagingException e) {
        throw new ModelibraException("Could not send an email: " + e.getMessage());
    } catch (IllegalStateException e) {
        throw new ModelibraException("Could not send an email: " + e.getMessage());
    }
}

From source file:org.eurekastreams.server.service.actions.strategies.EmailerFactory.java

/**
 * @param message//www  . j  a  v a  2 s.  c o m
 *            message to be sent.
 * @throws MessagingException
 *             Thrown if there are problems sending the message.
 */
public void sendMail(final MimeMessage message) throws MessagingException {
    Transport.send(message);
}

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

/**
 *
 * @param from the sender of the email./*from   w w w. j  a  v  a  2  s.co m*/
 * @param to the recipient of the email.
 * @param subject the subject of the email.
 * @param content the body of the email.
 * @throws SystemException if the email couldn't be sent due to some mail server exception.
 */
public void send(String from, String to, String subject, String content, String contentType, String encoding)
        throws SystemException {
    final Message message = createMessage(from, to, null, subject, content, contentType, encoding);

    try {
        Transport.send(message);
    } catch (MessagingException e) {
        e.printStackTrace();
        throw new SystemException("Unable to send message.", e);
    }

}

From source file:bioLockJ.module.agent.MailAgent.java

@Override
public void executeProjectFile() throws Exception {
    logFailures();/*from  w w  w.  ja  va 2s  . c om*/
    status = getStatus();
    Transport.send(getMimeMessage());
    Log.out.info("EMAIL SENT!");
}

From source file:com.cloudbees.demo.beesshop.service.MailService.java

public void sendOrderConfirmation(ShoppingCart shoppingCart, String recipient) {

    try {//w ww .  ja va  2  s . c om
        Message msg = new MimeMessage(mailSession);

        msg.setFrom(fromAddress);
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));

        msg.setSubject("[BeesShop] Order Confirmation: " + shoppingCart.getItems() + " items - "
                + shoppingCart.getPrettyPrice());

        String message = "ORDER CONFIRMATION\n" + "\n" + "* Purchased items: " + shoppingCart.getItemsCount()
                + "\n" + "* Price: " + shoppingCart.getPrettyPrice() + "\n";

        for (ShoppingCart.ShoppingCartItem item : shoppingCart.getItems()) {
            message += "   * " + item.getQuantity() + "x" + item.getProduct().getName() + "\n";
        }

        msg.setContent(message, "text/plain");

        Transport.send(msg);
        auditLogger.info("Sent to {} shopping cart with value of '{}'", recipient,
                shoppingCart.getPrettyPrice());
        sentEmailCounter.incrementAndGet();
    } catch (MessagingException e) {
        logger.warn("Exception sending order confirmation email to {}", recipient, e);
    }
}

From source file:gwtupload.sendmailsample.server.SendMailSampleServlet.java

@Override
public String executeAction(HttpServletRequest request, List<FileItem> sessionFiles)
        throws UploadActionException {
    try {//from w  ww.  j a  va 2 s .co m
        String from = null, to = null, subject = "", body = "";
        // create a new multipart content
        MimeMultipart multiPart = new MimeMultipart();
        for (FileItem item : sessionFiles) {
            if (item.isFormField()) {
                if ("from".equals(item.getFieldName()))
                    from = item.getString();
                if ("to".equals(item.getFieldName()))
                    to = item.getString();
                if ("subject".equals(item.getFieldName()))
                    subject = item.getString();
                if ("body".equals(item.getFieldName()))
                    body = item.getString();
            } else {
                // add the file part to multipart content
                MimeBodyPart part = new MimeBodyPart();
                part.setFileName(item.getName());
                part.setDataHandler(
                        new DataHandler(new ByteArrayDataSource(item.get(), item.getContentType())));
                multiPart.addBodyPart(part);
            }
        }

        // add the text part to multipart content
        MimeBodyPart txtPart = new MimeBodyPart();
        txtPart.setContent(body, "text/plain");
        multiPart.addBodyPart(txtPart);

        // configure smtp server
        Properties props = System.getProperties();
        props.put("mail.smtp.host", SMTP_SERVER);
        // create a new mail session and the mime message
        MimeMessage mime = new MimeMessage(Session.getInstance(props));
        mime.setText(body);
        mime.setContent(multiPart);
        mime.setSubject(subject);
        mime.setFrom(new InternetAddress(from));
        for (String rcpt : to.split("[\\s;,]+"))
            mime.addRecipient(Message.RecipientType.TO, new InternetAddress(rcpt));
        // send the message
        Transport.send(mime);
    } catch (MessagingException e) {
        throw new UploadActionException(e.getMessage());
    }
    return "Your mail has been sent successfuly.";
}

From source file:com.mnt.base.mail.MailHelper.java

public static void sendMail(String mailType, String mailTos, Map<String, Object> infoMap) {

    String[] mailtemplate = loadMailTemplate(mailType);

    if (mailtemplate != null && mailtemplate.length == 2) {
        String from = BaseConfiguration.getProperty("mail_server_email");
        String subject = buildMailContent(mailtemplate[0], infoMap, false);
        String mailContent = buildMailContent(mailtemplate[1], infoMap, true);

        Message msg = new MimeMessage(smtpSession);
        try {// ww w . j a  va2  s  . c om
            msg.setFrom(new InternetAddress(from));
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(mailTos, false));
            msg.setSubject(MimeUtility.encodeText(subject, "UTF-8", "B"));
            msg.setContent(mailContent, "text/html;charset=UTF-8");
            msg.setSentDate(new Date());

            Transport.send(msg);
        } catch (Exception e) {
            log.error("fail to send the mail: " + msg, e);
        }
    }
}