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:it.infn.ct.security.actions.ActivateAccount.java

private void sendMail(LDAPUser user, boolean enabled) throws MailException {
    javax.mail.Session session = null;/*from  w w w  .ja 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, idPAdmin));

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

        _log.error("mail bcc: " + mailBCC);
        String ccMail[] = mailBCC.split(";");
        InternetAddress mailCCopy[] = new InternetAddress[ccMail.length];
        for (int i = 0; i < ccMail.length; i++) {
            mailCCopy[i] = new InternetAddress(ccMail[i]);
        }

        mailMsg.setRecipients(Message.RecipientType.BCC, mailCCopy);

        mailMsg.setSubject(mailSubject);

        mailBody = mailBody.replaceAll("_USER_", user.getTitle() + " " + user.getGivenname() + " "
                + user.getSurname() + " (" + user.getUsername() + ")");
        if (enabled) {
            mailBody = mailBody.replace("_RESULT_", "accepted");
        } else {
            mailBody = mailBody.replace("_RESULT_", "denied");
        }
        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:it.infn.ct.security.actions.PassRecovery.java

private void sendMail(String code) throws MailException {
    javax.mail.Session session = null;//  w  ww .java  2  s .com
    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 {
        String title = user.getTitle() == null ? "" : user.getTitle();

        mailMsg.setFrom(new InternetAddress(mailFrom));

        InternetAddress mailTo[] = new InternetAddress[1];
        mailTo[0] = new InternetAddress(user.getPreferredMail(),
                title + user.getGivenname() + " " + user.getSurname());
        mailMsg.setRecipients(Message.RecipientType.TO, mailTo);

        mailMsg.setSubject(mailSubject);

        mailBody = mailBody.replaceAll("_USER_", title + " " + user.getGivenname() + " " + user.getSurname());
        mailBody = mailBody.replaceAll("_CODE_", code);

        mailMsg.setText(mailBody);

        Transport.send(mailMsg);

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

}

From source file:org.talend.dataprep.api.service.mail.MailFeedbackSender.java

@Override
public void send(String subject, String body, String sender) {
    try {//w w  w  .  j  av  a  2  s . co m
        final String recipientList = StringUtils.join((new HashSet<>(Arrays.asList(recipients))).toArray(),
                ',');
        subject = subjectPrefix + subject;
        body = bodyPrefix + "<br/>" + body + "<br/>" + bodySuffix;

        InternetAddress from = new InternetAddress(this.sender);
        InternetAddress replyTo = new InternetAddress(sender);

        Properties p = new Properties();
        p.put("mail.smtp.host", smtpHost);
        p.put("mail.smtp.port", smtpPort);
        p.put("mail.smtp.starttls.enable", "true");
        p.put("mail.smtp.auth", "true");

        MailAuthenticator authenticator = new MailAuthenticator(userName, password);
        Session sendMailSession = Session.getInstance(p, authenticator);

        MimeMessage msg = new MimeMessage(sendMailSession);
        msg.setFrom(from);
        msg.setReplyTo(new Address[] { replyTo });
        msg.addRecipients(Message.RecipientType.TO, recipientList);

        msg.setSubject(subject, "UTF-8");
        msg.setSentDate(new Date());
        Multipart mainPart = new MimeMultipart();
        BodyPart html = new MimeBodyPart();
        html.setContent(body, "text/html; charset=utf-8");
        mainPart.addBodyPart(html);
        msg.setContent(mainPart);
        Transport.send(msg);

        LOGGER.debug("Sending mail:'{}' to '{}'", subject, recipients);
    } catch (Exception e) {
        throw new TDPException(APIErrorCodes.UNABLE_TO_SEND_MAIL, e);
    }
}

From source file:uk.ac.cam.cl.dtg.util.Mailer.java

/**
 * Utility method to allow us to send multipart messages using HTML and plain text.
 *
 * //from w  w  w  . jav  a 2  s .com
 * @param recipient
 *            - string array of recipients that the message should be sent to
 * @param from
 *            - the e-mail address that should be used as the sending address
 * @param replyTo
 *            - (nullable) the e-mail address that should be used as the reply-to address
* @param replyToName
*            - (nullable) the name that should be used as the reply-to name
 * @param subject
 *            - The message subject
 * @param plainText
 *            - The message body
 * @param html
 *            - The message body in html
 * @throws MessagingException
 *             - if we cannot send the message for some reason.
 * @throws AddressException
 *             - if the address is not valid.
 */
public void sendMultiPartMail(final String[] recipient, final String from, @Nullable final String replyTo,
        @Nullable final String replyToName, final String subject, final String plainText, final String html)
        throws MessagingException, AddressException, UnsupportedEncodingException {
    Message msg = this.setupMessage(recipient, from, replyTo, replyToName, subject);

    // Create the text part
    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setText(plainText, "utf-8");

    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(html, "text/html; charset=utf-8");

    Multipart multiPart = new MimeMultipart("alternative");
    multiPart.addBodyPart(textPart);
    multiPart.addBodyPart(htmlPart);

    msg.setContent(multiPart);

    Transport.send(msg);
}

From source file:gov.nih.nci.cacis.cdw.CDWPendingLoader.java

public void loadPendingCDWDocuments(CDWLoader loader) {
    LOG.debug("Pending folder: " + cdwLoadPendingDirectory);
    LOG.info("SSSSSSS STARTED CDW LOAD SSSSSSSS");
    File pendingFolder = new File(cdwLoadPendingDirectory);
    FilenameFilter loadFileFilter = new FilenameFilter() {

        public boolean accept(File dir, String name) {
            return true;
        }//from ww  w  . j  a v  a 2 s  . c om
    };
    String[] loadFileNames = pendingFolder.list(loadFileFilter);
    LOG.info("Total Files to Load: " + loadFileNames.length);
    int filesLoaded = 0;
    int fileNumber = 0;
    for (String fileName : loadFileNames) {
        fileNumber++;
        LOG.info("Processing File [" + fileNumber + "] " + fileName);
        File loadFile = new File(cdwLoadPendingDirectory + "/" + fileName);
        try {
            final String[] params = StringUtils.split(fileName, "@@");
            String siteId = params[0];
            String studyId = params[1];
            String patientId = params[2];
            LOG.debug("SiteId: " + siteId);

            // the below code is not working, so parsing the file name for attributes.
            // DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            // DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            // Document document = documentBuilder.parse(loadFile);
            // XPathFactory factory = XPathFactory.newInstance();
            // XPath xPath = factory.newXPath();
            // String siteID = xPath.evaluate("/caCISRequest/clinicalMetaData/@siteIdRoot", document);

            loader.load(FileUtils.getStringFromFile(loadFile), loader.generateContext(), studyId, siteId,
                    patientId);
            LOG.info(String.format("Successfully processed file [%s] [%s] and moving into [%s]", fileNumber,
                    loadFile.getAbsolutePath(), cdwLoadProcessedDirectory));
            org.apache.commons.io.FileUtils.moveFileToDirectory(loadFile, new File(cdwLoadProcessedDirectory),
                    true);
            filesLoaded++;
        } catch (Exception e) {
            LOG.error(e.getMessage());
            e.printStackTrace();
            try {
                Properties props = new Properties();
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.host", cdwLoadSenderHost);
                props.put("mail.smtp.port", cdwLoadSenderPort);

                Session session = Session.getInstance(props, new javax.mail.Authenticator() {

                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(cdwLoadSenderUser, cdwLoadSenderPassword);
                    }
                });
                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(cdwLoadSenderAddress));
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(cdwLoadRecipientAddress));
                message.setSubject(cdwLoadNotificationSubject);
                message.setText(cdwLoadNotificationMessage + " [" + e.getMessage() + "]");

                Transport.send(message);
                org.apache.commons.io.FileUtils.moveFileToDirectory(loadFile, new File(cdwLoadErrorDirectory),
                        true);
                // TODO add logic to send email
            } catch (Exception e1) {
                LOG.error(e1.getMessage());
                e1.printStackTrace();
            }
        }
    }
    LOG.info("Files Successfully Loaded: " + filesLoaded);
    LOG.info("EEEEEEE ENDED CDW LOAD EEEEEEE");
}

From source file:org.collectionspace.chain.csp.webui.userdetails.UserDetailsReset.java

private Boolean doEmail(String csid, String emailparam, Request in, JSONObject userdetails)
        throws UIException, JSONException {

    String token = createToken(csid);
    EmailData ed = spec.getEmailData();/*from www .  ja  va 2s  . c  o  m*/
    String[] recipients = new String[1];

    /* ABSTRACT EMAIL STUFF : WHERE do we get the content of emails from? cspace-config.xml */
    String messagebase = ed.getPasswordResetMessage();
    String link = ed.getBaseURL() + ed.getLoginUrl() + "?token=" + token + "&email=" + emailparam;
    String message = messagebase.replaceAll("\\{\\{link\\}\\}", link);
    String greeting = userdetails.getJSONObject("fields").getString("screenName");
    message = message.replaceAll("\\{\\{greeting\\}\\}", greeting);
    message = message.replaceAll("\\\\n", "\\\n");
    message = message.replaceAll("\\\\r", "\\\r");

    String SMTP_HOST_NAME = ed.getSMTPHost();
    String SMTP_PORT = ed.getSMTPPort();
    String subject = ed.getPasswordResetSubject();
    String from = ed.getFromAddress();
    if (ed.getToAddress().isEmpty()) {
        recipients[0] = emailparam;
    } else {
        recipients[0] = ed.getToAddress();
    }
    Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
    boolean debug = false;

    Properties props = new Properties();
    props.put("mail.smtp.host", SMTP_HOST_NAME);
    props.put("mail.smtp.auth", ed.doSMTPAuth());
    props.put("mail.debug", ed.doSMTPDebug());
    props.put("mail.smtp.port", SMTP_PORT);

    Session session = Session.getDefaultInstance(props);
    // XXX fix to allow authpassword /username

    session.setDebug(debug);

    Message msg = new MimeMessage(session);
    InternetAddress addressFrom;
    try {
        addressFrom = new InternetAddress(from);
        msg.setFrom(addressFrom);

        InternetAddress[] addressTo = new InternetAddress[recipients.length];
        for (int i = 0; i < recipients.length; i++) {
            addressTo[i] = new InternetAddress(recipients[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addressTo);

        // Setting the Subject and Content Type
        msg.setSubject(subject);
        msg.setText(message);

        Transport.send(msg);
    } catch (AddressException e) {
        throw new UIException("AddressException: " + e.getMessage());
    } catch (MessagingException e) {
        throw new UIException("MessagingException: " + e.getMessage());
    }

    return true;
}

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

public void send(Message msg) {
    Properties properties = System.getProperties();
    properties.setProperty("mail.smtp.host", host);
    properties.setProperty("mail.transport.protocol", "smtp");

    if (username != null && !username.isEmpty()) {
        properties.setProperty("mail.user", username);
        properties.setProperty("mail.password", password);
    }/*ww  w  . j  a  v a  2s . c om*/

    if (port != null && !port.isEmpty()) {
        properties.setProperty("mail.smtp.port", port);
    }

    Session session = Session.getDefaultInstance(properties);
    MimeMessage message = new MimeMessage(session);
    try {
        message.setFrom(msg.getFrom());
        if (msg.getTo().size() > 1) {
            List<InternetAddress> addresses = msg.getTo();
            message.addRecipients(TO, addresses.toArray(new Address[addresses.size()]));
        } else {
            message.addRecipient(TO, msg.getTo().get(0));
        }
        if (msg.getBcc() != null && msg.getBcc().size() != 0) {
            if (msg.getTo().size() > 1) {
                List<InternetAddress> addresses = msg.getBcc();
                message.addRecipients(BCC, addresses.toArray(new Address[addresses.size()]));
            } else {
                message.addRecipient(TO, msg.getBcc().get(0));
            }
        }
        if (msg.getCc() != null && msg.getCc().size() > 0) {
            if (msg.getCc().size() > 1) {
                List<InternetAddress> addresses = msg.getCc();
                message.addRecipients(CC, addresses.toArray(new Address[addresses.size()]));
            } else {
                message.addRecipient(CC, msg.getCc().get(0));
            }
        }
        message.setSubject(msg.getSubject(), "UTF-8");
        MimeBodyPart mbp1 = new MimeBodyPart();
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();

        if (msg.getBodyType() == Message.BodyType.HTML_TEXT) {
            mbp1.setContent(msg.getBody(), "text/html");
        } else {
            mbp1.setText(msg.getBody(), "UTF-8");
        }
        if (port != null && !port.isEmpty()) {
            properties.setProperty("mail.smtp.port", port);
        }
        mp.addBodyPart(mbp1);
        if (msg.getAttachments().size() > 0) {
            for (String fileName : msg.getAttachments()) {
                // create the second message part
                MimeBodyPart mbpFile = new MimeBodyPart();
                // attach the file to the message
                FileDataSource fds = new FileDataSource(fileName);
                mbpFile.setDataHandler(new DataHandler(fds));
                mbpFile.setFileName(fds.getName());

                mp.addBodyPart(mbpFile);
            }
        }
        // add the Multipart to the message
        message.setContent(mp);

        if (username != null && !username.isEmpty()) {
            properties.setProperty("mail.user", username);
            properties.setProperty("mail.password", password);
            properties.put("mail.smtp.auth", auth);
            properties.put("mail.smtp.starttls.enable", starttls);
            Transport mailTransport = session.getTransport();
            mailTransport.connect(host, username, password);
            mailTransport.sendMessage(message, message.getAllRecipients());

        } else {
            Transport.send(message);
            log.debug("Message successfully sent.");
        }
    } catch (Throwable e) {
        log.error("Exception while sending mail", e);
    }
}

From source file:org.tizzit.util.mail.MailHelper.java

/**
 * Send an email in html-format in iso-8859-1-encoding
 * //from  w ww . j a  va2s. com
 * @param subject the subject of the new mail
 * @param htmlMessage the content of the mail as html
 * @param alternativeTextMessage the content of the mail as text
 * @param from the sender-address
 * @param to the receiver-address
 * @param cc the address of the receiver of a copy of this mail
 * @param bcc the address of the receiver of a blind-copy of this mail
 */
public static void sendHtmlMail(String subject, String htmlMessage, String alternativeTextMessage, String from,
        String to, String cc, String bcc) {
    try {
        MimeMessage msg = new MimeMessage(mailSession);
        msg.setFrom(new InternetAddress(from));
        if (cc != null && !cc.equals(""))
            msg.setRecipients(Message.RecipientType.CC, cc);
        if (bcc != null && !bcc.equals(""))
            msg.setRecipients(Message.RecipientType.BCC, bcc);
        msg.addRecipients(Message.RecipientType.TO, to);
        msg.setSubject(subject, "iso-8859-1");
        msg.setSentDate(new Date());

        MimeMultipart multiPart = new MimeMultipart();
        BodyPart bodyPart = new MimeBodyPart();

        bodyPart.setText(alternativeTextMessage);
        multiPart.addBodyPart(bodyPart);

        bodyPart = new MimeBodyPart();
        bodyPart.setContent(htmlMessage, "text/html");
        multiPart.addBodyPart(bodyPart);

        multiPart.setSubType("alternative");

        msg.setContent(multiPart);
        Transport.send(msg);
    } catch (Exception e) {
        log.error("Error sending html-mail: " + e.getLocalizedMessage());
    }
}

From source file:org.apache.synapse.transport.mail.MailEchoRawXMLTest.java

public void testRoundTripPOX() throws Exception {

    String msgId = UUIDGenerator.getUUID();

    Session session = Session.getInstance(props, new Authenticator() {
        public PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("synapse.test.1", "mailpassword");
        }/*from   www .ja  va 2 s.  c  om*/
    });
    session.setDebug(log.isTraceEnabled());

    WSMimeMessage msg = new WSMimeMessage(session);
    msg.setFrom(new InternetAddress("synapse.test.0@gmail.com"));
    msg.setReplyTo(InternetAddress.parse("synapse.test.0@gmail.com"));
    InternetAddress[] address = { new InternetAddress("synapse.test.6@gmail.com") };
    msg.setRecipients(Message.RecipientType.TO, address);
    msg.setSubject("POX Roundtrip");
    msg.setHeader(BaseConstants.SOAPACTION, Constants.AXIS2_NAMESPACE_URI + "/echoOMElement");
    msg.setSentDate(new Date());
    msg.setHeader(MailConstants.MAIL_HEADER_MESSAGE_ID, msgId);
    msg.setHeader(MailConstants.MAIL_HEADER_X_MESSAGE_ID, msgId);
    msg.setText(POX_MESSAGE);
    Transport.send(msg);

    Thread.yield();
    Thread.sleep(1000 * 10);

    Object reply = null;
    boolean replyNotFound = true;
    int retryCount = 3;
    while (replyNotFound) {
        log.debug("Checking for response ... with MessageID : " + msgId);
        reply = getMessage(msgId);
        if (reply != null) {
            replyNotFound = false;
        } else {
            if (retryCount-- > 0) {
                Thread.sleep(10000);
            } else {
                break;
            }
        }
    }

    if (reply != null && reply instanceof String) {
        log.debug("Result Body : " + reply);
        XMLStreamReader reader = StAXUtils.createXMLStreamReader(new StringReader((String) reply));
        OMElement res = new StAXOMBuilder(reader).getDocumentElement();
        if (res != null) {
            AXIOMXPath xpath = new AXIOMXPath("//my:myValue");
            xpath.addNamespace("my", "http://localhost/axis2/services/EchoXMLService");
            Object result = xpath.evaluate(res);
            if (result != null && result instanceof OMElement) {
                assertEquals("omTextValue", ((OMElement) result).getText());
            }
        }
    } else {
        fail("Did not receive the reply mail");
    }
}

From source file:org.libreplan.importers.notifications.ComposeMessage.java

public boolean composeMessageForUser(EmailNotification notification) {
    // Gather data about EmailTemplate needs to be used
    Resource resource = notification.getResource();
    EmailTemplateEnum type = notification.getType();
    Locale locale;//from www.  java 2s.co  m
    Worker currentWorker = getCurrentWorker(resource.getId());

    UserRole currentUserRole = getCurrentUserRole(notification.getType());

    if (currentWorker != null && currentWorker.getUser().isInRole(currentUserRole)) {
        if (currentWorker.getUser().getApplicationLanguage().equals(Language.BROWSER_LANGUAGE)) {
            locale = new Locale(System.getProperty("user.language"));
        } else {
            locale = new Locale(currentWorker.getUser().getApplicationLanguage().getLocale().getLanguage());
        }

        EmailTemplate currentEmailTemplate = findCurrentEmailTemplate(type, locale);

        if (currentEmailTemplate == null) {
            LOG.error("Email template is null");
            return false;
        }

        // Modify text that will be composed
        String text = currentEmailTemplate.getContent();
        text = replaceKeywords(text, currentWorker, notification);

        String receiver = currentWorker.getUser().getEmail();

        setupConnectionProperties();

        final String username = usrnme;
        final String password = psswrd;

        // It is very important to use Session.getInstance() instead of Session.getDefaultInstance()
        Session mailSession = Session.getInstance(properties, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        // Send message
        try {
            MimeMessage message = new MimeMessage(mailSession);

            message.setFrom(new InternetAddress(sender));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiver));

            String subject = currentEmailTemplate.getSubject();
            message.setSubject(subject);

            message.setText(text);

            Transport.send(message);

            return true;

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        } catch (NullPointerException e) {
            if (receiver == null) {
                Messagebox.show(
                        _(currentWorker.getUser().getLoginName() + " - this user have not filled E-mail"),
                        _("Error"), Messagebox.OK, Messagebox.ERROR);
            }
        }
    }
    return false;
}