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.github.sleroy.junit.mail.server.test.MailSender.java

/**
 * Send mail.// w  ww.ja  v a 2s. c  om
 *
 * @param from
 *            Sender's email ID needs to be mentioned
 * @param to
 *            Recipient's email ID needs to be mentioned.
 * @param subject
 *            the subject
 * @throws MessagingException
 */
public void sendMail(String from, String to, String subject, String body) throws MessagingException {

    // Get system properties
    Properties properties = System.getProperties();

    // Setup mail server
    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.smtp.port", Integer.toString(port));

    // Get the default Session object.
    Session session = Session.getDefaultInstance(properties);

    Transport transport = null;
    try {
        transport = session.getTransport();

        // Create a default MimeMessage object.
        MimeMessage 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(to));

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

        // Now set the actual message
        message.setText(body);

        // Send message
        transport.send(message);
        System.out.println("Sent message successfully....");
    } finally {
        if (transport != null) {
            transport.close();
        }
    }

}

From source file:org.latticesoft.util.resource.MessageUtil.java

public static void sendEmail(String fromAddr, String toAddr, String subject, String body,
        Properties mailConfig) {//w  w w . j a va2s  .  co  m
    try {
        //Here, no Authenticator argument is used (it is null).
        //Authenticators are used to prompt the user for user
        //name and password.
        Session session = Session.getDefaultInstance(mailConfig);
        MimeMessage message = new MimeMessage(session);
        //the "from" address may be set in code, or set in the
        //config file under "mail.from" ; here, the latter style is used
        message.setFrom(new InternetAddress(fromAddr));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddr));
        message.setSubject(subject);
        message.setText(body);
        Transport.send(message);
    } catch (MessagingException me) {
        if (log.isErrorEnabled()) {
            log.error(me);
        }
    }
}

From source file:SendMailBean.java

public void emailPassword(String email, String memberName, String password) {
    String host = "mail";
    String from = "w@j.com";

    Properties props = System.getProperties();

    props.put("mail.smtp.host", host);
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);

    try {/*from  w ww  .  j  a  v a 2 s .  c  o m*/
        message.setFrom(new InternetAddress(from));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));

        message.setSubject("Password Reminder");

        message.setText("Hi " + memberName + ",\nYour password is: " + password + "\nregards - " + from);
        Transport.send(message);
    } catch (AddressException ae) {
    } catch (MessagingException me) {
    }
}

From source file:com.agiletec.plugins.jpwebmail.aps.system.services.webmail.WebMailManager.java

@Override
public void sendMail(MimeMessage msg, String username, String password) throws ApsSystemException {
    //WebMailConfig config = this.getConfig();
    String smtpUsername = this.checkSmtpAuthUsername(username);
    String smtpPassword = this.checkSmtpAuthUserPassword(password);
    //String smtpUsername = (config.isSmtpEntandoUserAuth()) ? username : config.getSmtpUserName();
    //String smtpPassword = (config.isSmtpEntandoUserAuth()) ? password : config.getSmtpPassword();
    //Session session = this.createSession(true, smtpUsername, smtpPassword);
    Session session = (msg instanceof JpMimeMessage) ? ((JpMimeMessage) msg).getSession()
            : this.createSession(true, smtpUsername, smtpPassword);
    Transport bus = null;
    try {//w w w  .j  av a2s  .  c o  m
        bus = session.getTransport("smtp");
        //StringUtils.isEmpty(bus)
        if (StringUtils.isBlank(smtpUsername) && StringUtils.isBlank(smtpPassword)) {
            bus.connect();
        }
        /*
        if ((smtpUsername != null && smtpUsername.trim().length()>0) && 
              (smtpPassword != null && smtpPassword.trim().length()>0)) {
           if (port != null && port.intValue() > 0) {
              bus.connect(config.getSmtpHost(), port.intValue(), smtpUsername, smtpPassword);
           } else {
              bus.connect(config.getSmtpHost(), smtpUsername, smtpPassword);
           }
        } else {
           bus.connect();
        }
        */
        //bus.connect();
        msg.saveChanges();
        bus.send(msg);
    } catch (Throwable t) {
        _logger.error("Error sending mail", t);
        //ApsSystemUtils.logThrowable(t, this, "sendMail", "Error sending mail");
        throw new ApsSystemException("Error sending mail", t);
    } finally {
        closeTransport(bus);
    }
}

From source file:com.email.SendEmailNotification.java

/**
 * This sends a basic notification email that is just pure TEXT. Message is
 * sent from the section gathered//from  ww w.j  a  va  2s  .c  o m
 *
 * @param eml DocketNotificationModel
 */
public static void sendNotificationEmail(DocketNotificationModel eml) {
    //Get Account
    SystemEmailModel account = null;
    for (SystemEmailModel acc : Global.getSystemEmailParams()) {
        if (acc.getSection().equals(eml.getSection())) {
            account = acc;
            break;
        }
    }
    if (account != null) {
        String FROMaddress = account.getEmailAddress();
        String[] TOAddressess = ((eml.getSendTo() == null) ? "".split(";") : eml.getSendTo().split(";"));
        String subject = eml.getMessageSubject();
        String body = eml.getMessageBody();

        Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
        Properties properties = EmailProperties.setEmailOutProperties(account);

        Session session = Session.getInstance(properties, auth);
        MimeMessage email = new MimeMessage(session);

        try {
            for (String To : TOAddressess) {
                if (EmailValidator.getInstance().isValid(To)) {
                    email.addRecipient(Message.RecipientType.TO, new InternetAddress(To));
                }
            }

            email.setFrom(new InternetAddress(FROMaddress));
            email.setSubject(subject);
            email.setText(body);
            if (Global.isOkToSendEmail()) {
                Transport.send(email);
            } else {
                Audit.addAuditEntry("Notification Not Actually Sent: " + eml.getId() + " - " + subject);
            }

            DocketNotification.deleteEmailEntry(eml.getId());
        } catch (AddressException ex) {
            ExceptionHandler.Handle(ex);
        } catch (MessagingException ex) {
            ExceptionHandler.Handle(ex);
        }
    }
}

From source file:org.capelin.mvc.mail.SMTPMailSender.java

protected boolean send(String recipient, String body, boolean html) {
    Properties props = System.getProperties();
    props.put("mail.smtp.host", serverName);
    Session session = Session.getInstance(props, null);
    props.put("mail.from", sender);
    Message msg = new MimeMessage(session);
    try {//from ww  w.ja  va 2 s . com
        msg.setSubject(subject);
        msg.setFrom();
        msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient, false));
        if (html) {
            msg.setContent(new String(body.getBytes(), "iso-8859-1"), "text/html; charset=iso-8859-1");
        } else {
            msg.setText(body);
        }
        // Send the message:
        Transport.send(msg);
        log.debug("Email send to: " + sender);
        return true;
    } catch (MessagingException e) {
        log.info("Email Sending failed due to " + e);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

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

/**
 * Sends mail based upon input parameters.
 *
 * @param mailRecipients List of strings that are the recipient email addresses
 * @param from the from of the email/*from   w w w . java 2s .  co  m*/
 * @param mailSubject the subject of the email
 * @param mailBody the body of the email
 * @throws MessagingException thrown if there is a problem sending the message
 */
public static void sendMail(List<String> mailRecipients, String from, String mailSubject, String mailBody)
        throws MessagingException {
    MimeMessage message = constructMessage(mailRecipients, from, mailSubject);

    if (StringUtils.isEmpty(mailBody)) {
        LOG.info("No email body specified");
    }
    message.setText(mailBody);

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

From source file:org.openiam.idm.srvc.msg.service.MailSender.java

public void send(Message msg) {
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    Session session = Session.getDefaultInstance(properties);
    MimeMessage message = new MimeMessage(session);
    try {/* w  ww  .j a  v  a2 s. c o m*/
        message.setFrom(msg.getFrom());
        message.addRecipient(javax.mail.Message.RecipientType.TO, msg.getTo());
        message.setSubject(msg.getSubject());
        message.setText(msg.getBody());

        Transport.send(message);
        log.info("Message successfully sent.");
    } catch (MessagingException me) {
        log.error(me);
        me.printStackTrace();
    }
}

From source file:com.email.SendEmailCrashReport.java

/**
 * Sends crash email to predetermined list from the database.
 *
 * Also BCCs members of XLN team for notification of errors
 *//*w  ww.ja v  a  2  s .c  o  m*/
public static void sendCrashEmail() {
    //Get Account
    SystemEmailModel account = null;
    for (SystemEmailModel acc : Global.getSystemEmailParams()) {
        if (acc.getSection().equals("ERROR")) {
            account = acc;
            break;
        }
    }

    if (account != null) {
        String FROMaddress = account.getEmailAddress();
        List<String> TOAddresses = SystemErrorEmailList.getActiveEmailAddresses();
        String[] BCCAddressess = ("Anthony.Perk@XLNSystems.com".split(";"));
        String subject = "SERB 3.0 Application Daily Error Report for "
                + Global.getMmddyyyy().format(Calendar.getInstance().getTime());
        String body = buildBody();

        Authenticator auth = EmailAuthenticator.setEmailAuthenticator(account);
        Properties properties = EmailProperties.setEmailOutProperties(account);

        Session session = Session.getInstance(properties, auth);
        MimeMessage email = new MimeMessage(session);

        try {
            for (String TO : TOAddresses) {
                if (EmailValidator.getInstance().isValid(TO)) {
                    email.addRecipient(Message.RecipientType.TO, new InternetAddress(TO));
                }
            }

            for (String BCC : BCCAddressess) {
                if (EmailValidator.getInstance().isValid(BCC)) {
                    email.addRecipient(Message.RecipientType.BCC, new InternetAddress(BCC));
                }
            }

            email.setFrom(new InternetAddress(FROMaddress));
            email.setSubject(subject);
            email.setText(body);
            Transport.send(email);
        } catch (AddressException ex) {
            ExceptionHandler.Handle(ex);
        } catch (MessagingException ex) {
            ExceptionHandler.Handle(ex);
        }
    } else {
        System.out.println("No account found to send Error Email");
    }
}

From source file:org.openmrs.notification.mail.MailMessageSender.java

/**
 * Send the message.//from ww  w . j a  v a2  s  .co m
 *
 * @param message the message to be sent
 */
public void send(Message message) throws MessageException {
    try {
        MimeMessage mimeMessage = createMimeMessage(message);
        Transport.send(mimeMessage);
    } catch (Exception e) {
        log.error("failed to send message", e);

        // catch mail-specific exception and re-throw it as app-specific exception
        throw new MessageException(e);
    }
}