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:org.jenkinsci.plugins.send_mail_builder.SendMailBuilder.java

@Override
public boolean perform(final AbstractBuild<?, ?> build, final Launcher launcher, final BuildListener listener)
        throws IOException, InterruptedException {
    final EnvVars env = build.getEnvironment(listener);
    final String charset = Mailer.descriptor().getCharset();
    final MimeMessage msg = new MimeMessage(Mailer.descriptor().createSession());
    try {/*from  ww w .  j ava  2s.  co  m*/
        msg.setFrom(Mailer.StringToAddress(JenkinsLocationConfiguration.get().getAdminAddress(), charset));
        msg.setContent("", "text/plain");
        msg.setSentDate(new Date());
        String actualReplyTo = env.expand(replyTo);
        if (StringUtils.isBlank(actualReplyTo)) {
            actualReplyTo = Mailer.descriptor().getReplyToAddress();
        }
        if (StringUtils.isNotBlank(actualReplyTo)) {
            msg.setReplyTo(new Address[] { Mailer.StringToAddress(actualReplyTo, charset) });
        }
        msg.setRecipients(RecipientType.TO, toInternetAddresses(listener, env.expand(tos), charset));
        msg.setRecipients(RecipientType.CC, toInternetAddresses(listener, env.expand(ccs), charset));
        msg.setRecipients(RecipientType.BCC, toInternetAddresses(listener, env.expand(bccs), charset));
        msg.setSubject(env.expand(subject), charset);
        msg.setText(env.expand(text), charset);
        Transport.send(msg);
    } catch (final MessagingException e) {
        listener.getLogger().println(Messages.SendMail_FailedToSend());
        e.printStackTrace(listener.error(e.getMessage()));
        return false;
    }
    listener.getLogger().println(Messages.SendMail_SentSuccessfully());
    return true;
}

From source file:org.apache.falcon.plugin.EmailNotification.java

public void sendNotification(ResourceMessage resourceMessage, EntityNotification entityNotification)
        throws FalconException {
    try {//from w  w w .j  a  va2 s.co m
        message.addRecipients(Message.RecipientType.TO,
                NotificationUtil.getToAddress(entityNotification.getTo()));

        if (resourceMessage.getAction().equals("wf-instance-succeeded")) {
            sendSuccessNotification(resourceMessage);
        } else if ((resourceMessage.getAction().equals("wf-instance-failed"))) {
            sendFailureNotification(resourceMessage);
        }

        // Send message
        Transport.send(message);
    } catch (MessagingException e) {
        throw new FalconException("Error occurred while sending email message using SMTP:" + e);
    }
}

From source file:io.mapzone.arena.EMailHelpDashlet.java

protected void send() throws Exception {
    msg.addRecipients(RecipientType.TO, InternetAddress.parse(to.get(), false));
    msg.setSentDate(new Date());
    Transport.send(msg);
}

From source file:com.spartasystems.holdmail.util.TestMailClient.java

public void sendResourceEmail(String resourceName, String sender, String recipient, String subject) {

    try {//www  .  jav  a  2  s.com

        InputStream resource = TestMailClient.class.getClassLoader().getResourceAsStream(resourceName);
        if (resource == null) {
            throw new MessagingException("Couldn't find resource at: " + resourceName);
        }

        Message message = new MimeMessage(session, resource);

        // wipe out ALL exisitng recipients
        message.setRecipients(Message.RecipientType.TO, new Address[] {});
        message.setRecipients(Message.RecipientType.CC, new Address[] {});
        message.setRecipients(Message.RecipientType.BCC, new Address[] {});

        // then set the new data
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
        message.setFrom(InternetAddress.parse(sender)[0]);
        message.setSubject(subject);

        Transport.send(message);

        logger.info("Outgoing mail forwarded to " + recipient);

    } catch (MessagingException e) {
        throw new HoldMailException("couldn't send mail: " + e.getMessage(), e);
    }

}

From source file:com.sfs.ucm.service.MailService.java

/**
 * Send mail message in plain text. Mail host is obtained from instance-specific properties file via AppManager.
 * /*  ww  w .j  a  v  a 2 s  .com*/
 * @param fromAddress
 * @param ccRe
 * @param toRecipient
 * @param subject
 * @param body
 * @param messageType
 *            - text/plain or text/html
 * @return status message
 * @throws IllegalArgumentException
 */
@Asynchronous
public Future<String> sendMessage(final String fromAddress, final String ccRecipient, final String toRecipient,
        final String subject, final String body, final String messageType) throws IllegalArgumentException {

    // argument validation
    if (fromAddress == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined fromAddress");
    }
    if (toRecipient == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined toRecipient");
    }
    if (subject == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined subject");
    }
    if (body == null) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined body conent");
    }
    if (messageType == null || (!messageType.equals("text/plain") && !messageType.equals("text/html"))) {
        throw new IllegalArgumentException("sendMessage: Invalid or undefined messageType");
    }

    String status = null;

    try {
        Properties props = new Properties();
        props.put("mail.smtp.host", appManager.getApplicationProperty("mail.host"));
        props.put("mail.smtp.port", appManager.getApplicationProperty("mail.port"));

        Object[] params = new Object[4];
        params[0] = (String) subject;
        params[1] = (String) fromAddress;
        params[2] = (String) ccRecipient;
        params[3] = (String) toRecipient;
        logger.info("Sending message: subject: {}, fromAddress: {}, ccRecipient: {}, toRecipient: {}", params);

        Session session = Session.getDefaultInstance(props);
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(fromAddress));
        Address toAddress = new InternetAddress(toRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);

        if (StringUtils.isNotBlank(ccRecipient)) {
            Address ccAddress = new InternetAddress(ccRecipient);
            message.addRecipient(Message.RecipientType.CC, ccAddress);
        }
        message.setSubject(subject);
        message.setContent(body, messageType);
        Transport.send(message);
    } catch (AddressException e) {
        logger.error("sendMessage Address Exception occurred: {}", e.getMessage());
        status = "sendMessage Address Exception occurred";
    } catch (MessagingException e) {
        logger.error("sendMessage Messaging Exception occurred: {}", e.getMessage());
        status = "sendMessage Messaging Exception occurred";
    }

    return new AsyncResult<String>(status);

}

From source file:it.infn.ct.security.actions.ExtendAccount.java

private void sendMail() throws MailException {
    javax.mail.Session session = null;/*from w  w  w  .j  a  v a  2  s. co m*/
    try {
        Context initCtx = new InitialContext();
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        session = (javax.mail.Session) envCtx.lookup("mail/Users");

    } catch (Exception ex) {
        _log.error("Mail resource lookup error");
        _log.error(ex.getMessage());
        throw new MailException("Mail Resource not available");
    }

    Message mailMsg = new MimeMessage(session);
    try {
        mailMsg.setFrom(new InternetAddress(mailFrom, mailFrom));

        InternetAddress mailTos[] = new InternetAddress[1];
        mailTos[0] = new InternetAddress(mailTo);
        mailMsg.setRecipients(Message.RecipientType.TO, mailTos);

        mailMsg.setSubject(mailSubject);

        LDAPUser user = LDAPUtils.getUser(username);

        mailBody = mailBody.replaceAll("_USER_", user.getTitle() + " " + user.getGivenname() + " "
                + user.getSurname() + " (" + user.getUsername() + ")");

        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

    } catch (UnsupportedEncodingException ex) {
        _log.error(ex);
        throw new MailException("Mail address format not valid");
    } catch (MessagingException ex) {
        _log.error(ex);
        throw new MailException("Mail message has problems");
    }

}

From source file:com.norconex.jef4.mail.SimpleMailer.java

/**
 * Sends an email.//from  w  ww  .j  a v a  2s.  c om
 * @param recipients email recipients ("To" field)
 * @param subject email subject
 * @param body email body (content)
 * @throws MessagingException problem sending email
 */
public final void send(final String[] recipients, final String subject, final String body)
        throws MessagingException {
    if (recipients == null || recipients.length == 0) {
        throw new IllegalArgumentException("No mail recipient provided.");
    }
    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    message.setFrom(new InternetAddress(sender));
    for (int i = 0; i < recipients.length; i++) {
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipients[i]));
    }
    message.setSubject(subject);
    message.setContent(body, contentType);
    Transport.send(message);
}

From source file:org.codice.ddf.platform.email.impl.SmtpClientImpl.java

@Override
public Future<Void> send(Message message) {
    notNull(message, "message must be non-null");
    return executorService.submit(() -> {
        try {/* w  w  w  .j a v a  2s  .  c o m*/
            Transport.send(message);
        } catch (MessagingException e) {
            LOGGER.debug("Could not send message {}", message, e);
            return null;
        }

        SecurityLogger.audit("Sent an email: recipient={} subject={}",
                Arrays.toString(message.getAllRecipients()), message.getSubject());
        return null;
    });
}

From source file:hudson.tasks.MailSender.java

public boolean execute(AbstractBuild<?, ?> build, BuildListener listener) throws InterruptedException {
    try {/*w  w w .j  a  v  a  2 s .co m*/
        MimeMessage mail = getMail(build, listener);
        if (mail != null) {
            // if the previous e-mail was sent for a success, this new e-mail
            // is not a follow up
            AbstractBuild<?, ?> pb = build.getPreviousBuild();
            if (pb != null && pb.getResult() == Result.SUCCESS) {
                mail.removeHeader("In-Reply-To");
                mail.removeHeader("References");
            }

            Address[] allRecipients = mail.getAllRecipients();
            if (allRecipients != null) {
                StringBuilder buf = new StringBuilder("Sending e-mails to:");
                for (Address a : allRecipients)
                    buf.append(' ').append(a);
                listener.getLogger().println(buf);
                Transport.send(mail);

                build.addAction(new MailMessageIdAction(mail.getMessageID()));
            } else {
                listener.getLogger().println(Messages.MailSender_ListEmpty());
            }
        }
    } catch (MessagingException e) {
        e.printStackTrace(listener.error(e.getMessage()));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace(listener.error(e.getMessage()));
    } finally {
        CHECKPOINT.report();
    }

    return true;
}

From source file:com.linuxbox.enkive.statistics.StatsReportEmailer.java

public void sendReport() {

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

    // Setup mail server
    properties.setProperty("mail.smtp.host", mailHost);

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

    try { // 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.
        for (String toAddress : to.split(";")) {
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
        }/* www  .ja va 2 s . co  m*/

        // Set Subject: header field
        message.setSubject("Enkive Status Report");

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

        // Send message
        Transport.send(message);
    } catch (MessagingException mex) {
        LOGGER.warn("Error sending statistics report email", mex);
    }
}