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:mailhost.StartApp.java

public void sendEmail(String to, String subject, String body)
        throws UnsupportedEncodingException, MessagingException {

    System.out.println(String.format("Sending notification email recipients " + "to  " + to + " subject  "
            + subject + "host " + mailhost));

    if (StringUtils.isBlank(to))
        throw new IllegalArgumentException("The email request should have at least one recipient");

    Properties properties = new Properties();
    properties.setProperty("mail.smtp.host", mailhost);

    Session session = Session.getDefaultInstance(properties);
    Address[] a = new InternetAddress[1];
    a[0] = new InternetAddress("test@matson.com");

    MimeMessage message = new MimeMessage(session);

    message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
    message.addFrom(a);/*from w  w w  .ja va  2 s.c  om*/

    message.setSubject(subject);
    message.setContent(body, "text/html; charset=utf-8");
    //message.setText(body);

    // Send message
    Transport.send(message);
    System.out.println("Email sent.");
}

From source file:org.vosao.utils.EmailUtil.java

/**
 * Send email with html content and attachments.
 * @param htmlBody// w  w w .  ja v a 2s. c  o  m
 * @param subject
 * @param fromAddress
 * @param fromText
 * @param toAddress
 * @return null if OK or error message.
 */
public static String sendEmail(final String htmlBody, final String subject, final String fromAddress,
        final String fromText, final String toAddress, final List<FileItem> files) {

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    try {
        Multipart mp = new MimeMultipart();
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(htmlBody, "text/html");
        htmlPart.setHeader("Content-type", "text/html; charset=UTF-8");
        mp.addBodyPart(htmlPart);
        for (FileItem item : files) {
            MimeBodyPart attachment = new MimeBodyPart();
            attachment.setFileName(item.getFilename());
            String mimeType = MimeType.getContentTypeByExt(FolderUtil.getFileExt(item.getFilename()));
            DataSource ds = new ByteArrayDataSource(item.getData(), mimeType);
            attachment.setDataHandler(new DataHandler(ds));
            mp.addBodyPart(attachment);
        }
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromAddress, fromText));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress, toAddress));
        msg.setSubject(subject, "UTF-8");
        msg.setContent(mp);
        Transport.send(msg);
        return null;
    } catch (AddressException e) {
        return e.getMessage();
    } catch (MessagingException e) {
        return e.getMessage();
    } catch (UnsupportedEncodingException e) {
        return e.getMessage();
    }
}

From source file:com.duroty.application.files.manager.SendMessageThread.java

/**
 * <p>/*from   ww w.ja  v  a2 s .  c  om*/
 * Implementation of Thread.run()
 * </p>
 */
public void start() throws Exception {
    try {
        if (email != null) {
            email.getMimeMessage().removeHeader("X-DBox");
            email.send();

            return;
        }

        if (mime != null) {
            mime.removeHeader("X-DBox");
            Transport.send(mime);

            return;
        }

        if (mimes != null) {
            for (int i = 0; i < mimes.size(); i++) {
                MimeMessage mm = (MimeMessage) mimes.get(i);
                mm.removeHeader("X-DBox");
                Transport.send(mm);
            }
        }
    } catch (Exception ex) {
        throw new MailException(ex);
    } catch (java.lang.OutOfMemoryError ex) {
        System.gc();
        throw new MailException(ex);
    } catch (Throwable ex) {
        throw new MailException(ex);
    } finally {
        System.gc();
    }
}

From source file:EmailBean.java

public void sendMessage() throws Exception {

    Properties properties = System.getProperties();

    //populate the 'Properties' object with the mail
    //server address, so that the default 'Session'
    //instance can use it.
    properties.put("mail.smtp.host", smtpHost);

    Session session = Session.getDefaultInstance(properties);

    Message mailMsg = new MimeMessage(session);//a new email message

    InternetAddress[] addresses = null;// w  ww .j  a v a 2  s . com

    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));

        } else {

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

        }

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

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

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

    } catch (Exception exc) {

        throw exc;

    }

}

From source file:org.vosao.utils.EmailUtil.java

/**
 * Send email with html content and attachments.
 * @param htmlBody/*from   w  w  w. j av  a  2  s. com*/
 * @param subject
 * @param fromAddress
 * @param fromText
 * @param toAddress
 * @return null if OK or error message.
 */
public static String sendEmail(final String htmlBody, final String subject, final String fromAddress,
        final String fromText, final String toAddress, final List<FileItem> files) {

    Properties props = new Properties();
    Session session = Session.getDefaultInstance(props, null);
    try {
        Multipart mp = new MimeMultipart();
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(htmlBody, "text/html");
        htmlPart.setHeader("Content-type", "text/html; charset=UTF-8");
        mp.addBodyPart(htmlPart);
        for (FileItem item : files) {
            MimeBodyPart attachment = new MimeBodyPart();
            attachment.setFileName(item.getFilename());
            String mimeType = MimeType.getContentTypeByExt(FolderUtil.getFileExt(item.getFilename()));
            if (mimeType.equals("text/plain")) {
                mimeType = MimeType.DEFAULT;
            }
            DataSource ds = new ByteArrayDataSource(item.getData(), mimeType);
            attachment.setDataHandler(new DataHandler(ds));
            mp.addBodyPart(attachment);
        }
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromAddress, fromText));
        msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress, toAddress));
        msg.setSubject(subject, "UTF-8");
        msg.setContent(mp);
        Transport.send(msg);
        return null;
    } catch (AddressException e) {
        return e.getMessage();
    } catch (MessagingException e) {
        return e.getMessage();
    } catch (UnsupportedEncodingException e) {
        return e.getMessage();
    }
}

From source file:de.fzi.ALERT.actor.ActionActuator.MailService.java

public void sendEmail(Authenticator auth, String address, String subject, String content) {
    try {//  w ww .  j  a va 2 s .com
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", true);
        props.put("mail.smtp.starttls.enable", "true");

        Session session = Session.getDefaultInstance(props, auth);
        // -- Create a new message --
        Message msg = new MimeMessage(session);

        // -- Set the FROM and TO fields --
        msg.setFrom(new InternetAddress(username));
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(address, false));

        // -- Set the subject and body text --
        msg.setSubject(subject);
        msg.setText(content);

        // -- Set some other header information --
        msg.setHeader("X-Mailer", "LOTONtechEmail");
        msg.setSentDate(new Date());

        // -- Send the message --
        Transport.send(msg);

        System.out.println("An announce Mail has been send to " + address);
    } catch (AddressException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:gov.nih.nci.caarray.util.EmailUtil.java

/**
 * Sends a multipart email with both HTML and plain-text bodies based upon input parameters.
 *
 * @param mailRecipients List of strings that are the recipient email addresses
 * @param from the from of the email/*from ww w . j a va 2  s .c  o  m*/
 * @param mailSubject the subject of the email
 * @param htmlMailBody the HTML version of the body of the email
 * @param plainMailBody the plain-text version of the body of the email
 * @throws MessagingException thrown if there is a problem sending the message
 */
public static void sendMultipartMail(List<String> mailRecipients, String from, String mailSubject,
        String htmlMailBody, String plainMailBody) throws MessagingException {
    MimeMessage message = constructMessage(mailRecipients, from, mailSubject);

    Multipart mp = new MimeMultipart("alternative");
    addBodyPart(mp, htmlMailBody, "text/html");
    addBodyPart(mp, plainMailBody, "text/plain");
    message.setContent(mp);

    LOG.debug("sending email");
    Transport.send(message);
    LOG.debug("email successfully sent");
}

From source file:com.email.SendEmailCalInvite.java

/**
 * Sends email based off of the section it comes from. This creates a
 * calendar invite object that is interactive by Outlook.
 *
 * @param eml EmailOutInviteModel/*from w w w  . j  a  va  2  s.c o  m*/
 */
public static void sendCalendarInvite(EmailOutInvitesModel eml) {
    SystemEmailModel account = null;

    //Get Account
    for (SystemEmailModel acc : Global.getSystemEmailParams()) {
        if (acc.getSection().equals(eml.getSection())) {
            account = acc;
            break;
        }
    }
    if (account != null) {
        //Get parts
        String FromAddress = account.getEmailAddress();
        String[] TOAddressess = ((eml.getToAddress() == null) ? "".split(";") : eml.getToAddress().split(";"));
        String[] CCAddressess = ((eml.getCcAddress() == null) ? "".split(";") : eml.getCcAddress().split(";"));
        String emailSubject = "";
        BodyPart emailBody = body(eml);
        BodyPart inviteBody = null;

        if (eml.getHearingRoomAbv() == null) {
            emailSubject = eml.getEmailSubject() == null
                    ? (eml.getEmailBody() == null ? eml.getCaseNumber() : eml.getEmailBody())
                    : eml.getEmailSubject();
            inviteBody = responseDueCalObject(eml, account);
        } else {
            emailSubject = eml.getEmailSubject() == null ? Subject(eml) : eml.getEmailSubject();
            inviteBody = inviteCalObject(eml, account, emailSubject);
        }

        //Set Email Parts
        Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
        Properties properties = EmailProperties.setEmailOutProperties(account);
        Session session = Session.getInstance(properties, auth);
        MimeMessage smessage = new MimeMessage(session);
        Multipart multipart = new MimeMultipart("alternative");
        try {
            smessage.addFrom(new InternetAddress[] { new InternetAddress(FromAddress) });
            for (String To : TOAddressess) {
                if (EmailValidator.getInstance().isValid(To)) {
                    smessage.addRecipient(Message.RecipientType.TO, new InternetAddress(To));
                }
            }
            for (String Cc : CCAddressess) {
                if (EmailValidator.getInstance().isValid(Cc)) {
                    smessage.addRecipient(Message.RecipientType.CC, new InternetAddress(Cc));
                }
            }
            smessage.setSubject(emailSubject);
            multipart.addBodyPart(emailBody);
            multipart.addBodyPart(inviteBody);
            smessage.setContent(multipart);
            if (Global.isOkToSendEmail()) {
                Transport.send(smessage);
            } else {
                Audit.addAuditEntry("Cal Invite Not Actually Sent: " + eml.getId() + " - " + emailSubject);
            }
            EmailOutInvites.deleteEmailEntry(eml.getId());
        } catch (AddressException ex) {
            ExceptionHandler.Handle(ex);
        } catch (MessagingException ex) {
            ExceptionHandler.Handle(ex);
        }
    }
}

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

@Override
public void sendCardDetailsMessage(String emailAddress) {
    Session session = _authenticateOutboundEmailAddress();

    try {//from w ww .  j  a  v a 2s . c o  m
        Message emailMessage = _populateMessage(emailAddress, "Card Details Updated", "card_details_email.vm",
                session);

        Transport.send(emailMessage);
    } catch (Exception e) {
        _log.error("Unable to send card details message", e);
    }
}

From source file:com.googlecode.psiprobe.tools.Mailer.java

public void send(MailMessage mailMessage) throws MessagingException {
    Properties props = (Properties) System.getProperties().clone();
    if (smtp != null) {
        props.put(PROPERTY_KEY_SMTP, smtp);
    }/*from  www  . j a  v  a  2  s .  c  o  m*/
    PrintStream debugOut = LogOutputStream.createPrintStream(log, LogOutputStream.LEVEL_DEBUG);

    Session session = Session.getDefaultInstance(props);
    session.setDebug(true);
    session.setDebugOut(debugOut);

    MimeMessage message = createMimeMessage(session, mailMessage);
    log.debug("Sending message");
    Transport.send(message);
}