Example usage for javax.mail Transport sendMessage

List of usage examples for javax.mail Transport sendMessage

Introduction

In this page you can find the example usage for javax.mail Transport sendMessage.

Prototype

public abstract void sendMessage(Message msg, Address[] addresses) throws MessagingException;

Source Link

Document

Send the Message to the specified list of addresses.

Usage

From source file:org.exist.xquery.modules.mail.SendEmailFunction.java

public Sequence sendEmail(Sequence[] args, Sequence contextSequence) throws XPathException {
    // was a session handle specified?
    if (args[0].isEmpty()) {
        throw (new XPathException(this, "Session handle not specified"));
    }/*  w w w . j av  a 2 s. c  o m*/

    // get the Session
    long sessionHandle = ((IntegerValue) args[0].itemAt(0)).getLong();
    Session session = MailModule.retrieveSession(context, sessionHandle);
    if (session == null) {
        throw (new XPathException(this, "Invalid Session handle specified"));
    }

    try {
        List<Message> messages = parseInputEmails(session, args[1]);
        String proto = session.getProperty("mail.transport.protocol");
        if (proto == null)
            proto = "smtp";
        Transport t = session.getTransport(proto);
        try {
            if (session.getProperty("mail." + proto + ".auth") != null)
                t.connect(session.getProperty("mail." + proto + ".user"),
                        session.getProperty("mail." + proto + ".password"));
            for (Message msg : messages) {
                t.sendMessage(msg, msg.getAllRecipients());
            }
        } finally {
            t.close();
        }

        return (Sequence.EMPTY_SEQUENCE);
    } catch (TransformerException te) {
        throw new XPathException(this, "Could not Transform XHTML Message Body: " + te.getMessage(), te);
    } catch (MessagingException smtpe) {
        throw new XPathException(this, "Could not send message(s): " + smtpe.getMessage(), smtpe);
    } catch (IOException ioe) {
        throw new XPathException(this, "Attachment in some message could not be prepared: " + ioe.getMessage(),
                ioe);
    } catch (Throwable t) {
        throw new XPathException(this,
                "Unexpected error from JavaMail layer (Is your message well structured?): " + t.getMessage(),
                t);
    }
}

From source file:org.jumpmind.metl.core.runtime.flow.FlowRuntime.java

protected void sendNotifications(Notification.EventType eventType) {
    if (notifications != null && notifications.size() > 0) {
        Transport transport = null;
        Date date = new Date();
        flowParameters.put("_date", DateFormatUtils.format(date, DATE_FORMAT));
        flowParameters.put("_time", DateFormatUtils.format(date, TIME_FORMAT));

        try {//from   w  w w . j ava  2s.  co  m
            for (Notification notification : notifications) {
                if (notification.getEventType().equals(eventType.toString())) {
                    log.info("Sending notification '" + notification.getName() + "' of level '"
                            + notification.getLevel() + "' and type '" + notification.getNotifyType() + "'");
                    transport = mailSession.getTransport();
                    MimeMessage message = new MimeMessage(mailSession.getSession());
                    message.setSentDate(new Date());
                    message.setRecipients(RecipientType.BCC, notification.getRecipients());
                    message.setSubject(
                            FormatUtils.replaceTokens(notification.getSubject(), flowParameters, true));
                    message.setText(FormatUtils.replaceTokens(notification.getMessage(), flowParameters, true));
                    try {
                        transport.sendMessage(message, message.getAllRecipients());
                    } catch (MessagingException e) {
                        log.error("Failure while sending notification", e);
                    }
                }
            }
        } catch (MessagingException e) {
            log.error("Failure while preparing notification", e);
        } finally {
            mailSession.closeTransport(transport);
        }
    }
}

From source file:org.projectforge.mail.SendMail.java

private void sendIt(final Mail composedMessage) {
    final Session session = Session.getInstance(properties);
    Transport transport = null;
    try {//from   w  ww. j  a  v  a2  s  .c o  m
        MimeMessage message = new MimeMessage(session);
        if (composedMessage.getFrom() != null) {
            message.setFrom(new InternetAddress(composedMessage.getFrom()));
        } else {
            message.setFrom();
        }
        message.setRecipients(Message.RecipientType.TO, composedMessage.getTo());
        String subject;
        subject = composedMessage.getSubject();
        /*
         * try { subject = MimeUtility.encodeText(composedMessage.getSubject()); } catch (UnsupportedEncodingException ex) {
         * log.error("Exception encountered while encoding subject." + ex, ex); subject = composedMessage.getSubject(); }
         */
        message.setSubject(subject, sendMailConfig.getCharset());
        message.setSentDate(new Date());
        if (composedMessage.getContentType() != null) {
            message.setText(composedMessage.getContent(), composedMessage.getCharset(),
                    composedMessage.getContentType());
        } else {
            message.setText(composedMessage.getContent(), sendMailConfig.getCharset());
        }
        message.saveChanges(); // don't forget this
        transport = session.getTransport();
        if (StringUtils.isNotEmpty(sendMailConfig.getUser()) == true) {
            transport.connect(sendMailConfig.getUser(), sendMailConfig.getPassword());
        } else {
            transport.connect();
        }
        transport.sendMessage(message, message.getAllRecipients());
    } catch (MessagingException ex) {
        log.error("While creating and sending message: " + composedMessage.toString(), ex);
        throw new InternalErrorException("mail.error.exception");
    } finally {
        if (transport != null) {
            try {
                transport.close();
            } catch (MessagingException ex) {
                log.error("While creating and sending message: " + composedMessage.toString(), ex);
                throw new InternalErrorException("mail.error.exception");
            }
        }
    }
    log.info("E-Mail successfully sent: " + composedMessage.toString());
}

From source file:org.masukomi.aspirin.core.RemoteDelivery.java

/**
 * We can assume that the recipients of this message are all going to the
 * same mail server. We will now rely on the JNDI to do DNS MX record lookup
 * and try to deliver to the multiple mail servers. If it fails, it should
 * throw an exception.//from   w  w  w .  jav a 2 s.c  o m
 * 
 * Creation date: (2/24/00 11:25:00 PM)
 * 
 * @param mail
 *            org.apache.james.core.MailImpl
 * @param session
 *            javax.mail.Session
 * @return boolean Whether the delivery was successful and the message can
 *         be deleted
 */
private boolean deliver(QuedItem qi, Session session) {
    MailAddress rcpt = null;
    try {
        if (log.isDebugEnabled()) {
            log.debug("entering RemoteDelivery.deliver(QuedItem qi, Session session)");
        }
        MailImpl mail = (MailImpl) qi.getMail();
        MimeMessage message = mail.getMessage();
        // Create an array of the recipients as InternetAddress objects
        Collection recipients = mail.getRecipients();
        InternetAddress addr[] = new InternetAddress[recipients.size()];
        int j = 0;
        // funky ass look because you can't getElementAt() in a Collection

        for (Iterator i = recipients.iterator(); i.hasNext(); j++) {
            MailAddress currentRcpt = (MailAddress) i.next();
            addr[j] = currentRcpt.toInternetAddress();
        }
        if (addr.length <= 0) {
            if (log.isDebugEnabled()) {
                log.debug("No recipients specified... returning");
            }
            return true;
        }
        // Figure out which servers to try to send to. This collection
        // will hold all the possible target servers
        Collection targetServers = null;
        Iterator it = recipients.iterator();
        while (it.hasNext()) {
            rcpt = (MailAddress) recipients.iterator().next();
            if (!qi.recepientHasBeenHandled(rcpt)) {
                break;
            }
        }
        // theoretically it is possible to not hav eone that hasn't been
        // handled
        // however that's only if something has gone really wrong.
        if (rcpt != null) {
            String host = rcpt.getHost();
            // Lookup the possible targets
            try {
                // targetServers = MXLookup.urlsForHost(host); // farking
                // unreliable jndi bs
                targetServers = getMXRecordsForHost(host);
            } catch (Exception e) {
                log.error(e);
            }
            if (targetServers == null || targetServers.size() == 0) {
                log.warn("No mail server found for: " + host);
                StringBuffer exceptionBuffer = new StringBuffer(128)
                        .append("I found no MX record entries for the hostname ").append(host)
                        .append(".  I cannot determine where to send this message.");
                return failMessage(qi, rcpt, new MessagingException(exceptionBuffer.toString()), true);
            } else if (log.isTraceEnabled()) {
                log.trace(targetServers.size() + " servers found for " + host);
            }
            MessagingException lastError = null;
            Iterator i = targetServers.iterator();
            while (i.hasNext()) {
                try {
                    URLName outgoingMailServer = (URLName) i.next();
                    StringBuffer logMessageBuffer = new StringBuffer(256).append("Attempting delivery of ")
                            .append(mail.getName()).append(" to host ").append(outgoingMailServer.toString())
                            .append(" to addresses ").append(Arrays.asList(addr));
                    if (log.isDebugEnabled()) {
                        log.debug(logMessageBuffer.toString());
                    }
                    ;
                    // URLName urlname = new URLName("smtp://"
                    // + outgoingMailServer);
                    Properties props = session.getProperties();
                    if (mail.getSender() == null) {
                        props.put("mail.smtp.from", "<>");
                    } else {
                        String sender = mail.getSender().toString();
                        props.put("mail.smtp.from", sender);
                    }
                    // Many of these properties are only in later JavaMail
                    // versions
                    // "mail.smtp.ehlo" //default true
                    // "mail.smtp.auth" //default false
                    // "mail.smtp.dsn.ret" //default to nothing... appended
                    // as
                    // RET= after MAIL FROM line.
                    // "mail.smtp.dsn.notify" //default to
                    // nothing...appended as
                    // NOTIFY= after RCPT TO line.
                    Transport transport = null;
                    try {
                        transport = session.getTransport(outgoingMailServer);
                        try {
                            transport.connect();
                        } catch (MessagingException me) {
                            log.error(me);
                            // Any error on connect should cause the mailet
                            // to
                            // attempt
                            // to connect to the next SMTP server associated
                            // with this MX record,
                            // assuming the number of retries hasn't been
                            // exceeded.
                            if (failMessage(qi, rcpt, me, false)) {
                                return true;
                            } else {
                                continue;
                            }
                        }
                        transport.sendMessage(message, addr);
                        // log.debug("message sent to " +addr);
                        /*TODO: catch failures that should result 
                         * in failure with no retries
                         } catch (SendFailedException sfe){
                           qi.failForRecipient(que, );
                           */
                    } finally {
                        if (transport != null) {
                            transport.close();
                            transport = null;
                        }
                    }
                    logMessageBuffer = new StringBuffer(256).append("Mail (").append(mail.getName())
                            .append(") sent successfully to ").append(outgoingMailServer);
                    log.debug(logMessageBuffer.toString());
                    qi.succeededForRecipient(que, rcpt);
                    return true;
                } catch (MessagingException me) {
                    log.error(me);
                    // MessagingException are horribly difficult to figure
                    // out
                    // what actually happened.
                    StringBuffer exceptionBuffer = new StringBuffer(256)
                            .append("Exception delivering message (").append(mail.getName()).append(") - ")
                            .append(me.getMessage());
                    log.warn(exceptionBuffer.toString());
                    if ((me.getNextException() != null)
                            && (me.getNextException() instanceof java.io.IOException)) {
                        // This is more than likely a temporary failure
                        // If it's an IO exception with no nested exception,
                        // it's probably
                        // some socket or weird I/O related problem.
                        lastError = me;
                        continue;
                    }
                    // This was not a connection or I/O error particular to
                    // one
                    // SMTP server of an MX set. Instead, it is almost
                    // certainly
                    // a protocol level error. In this case we assume that
                    // this
                    // is an error we'd encounter with any of the SMTP
                    // servers
                    // associated with this MX record, and we pass the
                    // exception
                    // to the code in the outer block that determines its
                    // severity.
                    throw me;
                } // end catch
            } // end while
              // If we encountered an exception while looping through,
              // throw the last MessagingException we caught. We only
              // do this if we were unable to send the message to any
              // server. If sending eventually succeeded, we exit
              // deliver() though the return at the end of the try
              // block.
            if (lastError != null) {
                throw lastError;
            }
        } // END if (rcpt != null)
        else {
            log.error("unable to find recipient that handn't already been handled");
        }
    } catch (SendFailedException sfe) {
        log.error(sfe);
        boolean deleteMessage = false;
        Collection recipients = qi.getMail().getRecipients();
        // Would like to log all the types of email addresses
        if (log.isDebugEnabled()) {
            log.debug("Recipients: " + recipients);
        }
        /*
         * The rest of the recipients failed for one reason or another.
         * 
         * SendFailedException actually handles this for us. For example, if
         * you send a message that has multiple invalid addresses, you'll
         * get a top-level SendFailedException that that has the valid,
         * valid-unsent, and invalid address lists, with all of the server
         * response messages will be contained within the nested exceptions.
         * [Note: the content of the nested exceptions is implementation
         * dependent.]
         * 
         * sfe.getInvalidAddresses() should be considered permanent.
         * sfe.getValidUnsentAddresses() should be considered temporary.
         * 
         * JavaMail v1.3 properly populates those collections based upon the
         * 4xx and 5xx response codes.
         * 
         */
        if (sfe.getInvalidAddresses() != null) {
            Address[] address = sfe.getInvalidAddresses();
            if (address.length > 0) {
                recipients.clear();
                for (int i = 0; i < address.length; i++) {
                    try {
                        recipients.add(new MailAddress(address[i].toString()));
                    } catch (ParseException pe) {
                        // this should never happen ... we should have
                        // caught malformed addresses long before we
                        // got to this code.
                        if (log.isDebugEnabled()) {
                            log.debug("Can't parse invalid address: " + pe.getMessage());
                        }
                    }
                }
                if (log.isDebugEnabled()) {
                    log.debug("Invalid recipients: " + recipients);
                }
                deleteMessage = failMessage(qi, rcpt, sfe, true);
            }
        }
        if (sfe.getValidUnsentAddresses() != null) {
            Address[] address = sfe.getValidUnsentAddresses();
            if (address.length > 0) {
                recipients.clear();
                for (int i = 0; i < address.length; i++) {
                    try {
                        recipients.add(new MailAddress(address[i].toString()));
                    } catch (ParseException pe) {
                        // this should never happen ... we should have
                        // caught malformed addresses long before we
                        // got to this code.
                        if (log.isDebugEnabled()) {
                            log.debug("Can't parse unsent address: " + pe.getMessage());
                        }
                        pe.printStackTrace();
                    }
                }
                if (log.isDebugEnabled()) {
                    log.debug("Unsent recipients: " + recipients);
                }
                deleteMessage = failMessage(qi, rcpt, sfe, false);
            }
        }
        return deleteMessage;
    } catch (MessagingException ex) {
        log.error(ex);
        // We should do a better job checking this... if the failure is a
        // general
        // connect exception, this is less descriptive than more specific
        // SMTP command
        // failure... have to lookup and see what are the various Exception
        // possibilities
        // Unable to deliver message after numerous tries... fail
        // accordingly
        // We check whether this is a 5xx error message, which
        // indicates a permanent failure (like account doesn't exist
        // or mailbox is full or domain is setup wrong).
        // We fail permanently if this was a 5xx error
        return failMessage(qi, rcpt, ex, ('5' == ex.getMessage().charAt(0)));
    } catch (Throwable t) {
        log.error(t);
    }
    /*
     * If we get here, we've exhausted the loop of servers without sending
     * the message or throwing an exception. One case where this might
     * happen is if we get a MessagingException on each transport.connect(),
     * e.g., if there is only one server and we get a connect exception.
     * Return FALSE to keep run() from deleting the message.
     */
    return false;
}

From source file:org.pentaho.di.trans.steps.mail.Mail.java

public void sendMail(Object[] r, String server, int port, String senderAddress, String senderName,
        String destination, String destinationCc, String destinationBCc, String contactPerson,
        String contactPhone, String authenticationUser, String authenticationPassword, String mailsubject,
        String comment, String replyToAddresses) throws Exception {

    // Send an e-mail...
    // create some properties and get the default Session

    String protocol = "smtp";
    if (meta.isUsingSecureAuthentication()) { // PDI-2955
        // if (meta.isUsingAuthentication()) {
        if (meta.getSecureConnectionType().equals("TLS")) {
            // Allow TLS authentication
            data.props.put("mail.smtp.starttls.enable", "true");
        } else {//from w ww.  j av a  2s.c o  m
            protocol = "smtps";
            // required to get rid of a SSL exception :
            // nested exception is:
            // javax.net.ssl.SSLException: Unsupported record version Unknown
            data.props.put("mail.smtps.quitwait", "false");
        }
    }
    data.props.put("mail." + protocol + ".host", server);
    if (port != -1) {
        data.props.put("mail." + protocol + ".port", "" + port); // needs to be supplied as a string, not as an integer
    }

    if (isDebug()) {
        data.props.put("mail.debug", "true");
    }

    if (meta.isUsingAuthentication()) {
        data.props.put("mail." + protocol + ".auth", "true");
    }

    Session session = Session.getInstance(data.props);
    session.setDebug(isDebug());

    // create a message
    Message msg = new MimeMessage(session);

    // set message priority
    if (meta.isUsePriority()) {
        String priority_int = "1";
        if (meta.getPriority().equals("low")) {
            priority_int = "3";
        }
        if (meta.getPriority().equals("normal")) {
            priority_int = "2";
        }

        msg.setHeader("X-Priority", priority_int); // (String)int between 1= high and 3 = low.
        msg.setHeader("Importance", meta.getImportance());
        // seems to be needed for MS Outlook.
        // where it returns a string of high /normal /low.
        msg.setHeader("Sensitivity", meta.getSensitivity());
        // Possible values are normal, personal, private, company-confidential
    }

    // set Email sender
    String email_address = senderAddress;
    if (!Const.isEmpty(email_address)) {
        // get sender name
        if (!Const.isEmpty(senderName)) {
            email_address = senderName + '<' + email_address + '>';
        }
        msg.setFrom(new InternetAddress(email_address));
    } else {
        throw new MessagingException(BaseMessages.getString(PKG, "Mail.Error.ReplyEmailNotFilled"));
    }

    // Set reply to
    if (!Const.isEmpty(replyToAddresses)) {
        // get replay to
        // Split the mail-address: space separated
        String[] reply_Address_List = replyToAddresses.split(" ");
        InternetAddress[] address = new InternetAddress[reply_Address_List.length];

        for (int i = 0; i < reply_Address_List.length; i++) {
            address[i] = new InternetAddress(reply_Address_List[i]);
        }

        // To add the real reply-to
        msg.setReplyTo(address);
    }

    // Split the mail-address: space separated
    String[] destinations = destination.split(" ");
    InternetAddress[] address = new InternetAddress[destinations.length];
    for (int i = 0; i < destinations.length; i++) {
        address[i] = new InternetAddress(destinations[i]);
    }

    msg.setRecipients(Message.RecipientType.TO, address);

    String realdestinationCc = destinationCc;
    if (!Const.isEmpty(realdestinationCc)) {
        // Split the mail-address Cc: space separated
        String[] destinationsCc = realdestinationCc.split(" ");
        InternetAddress[] addressCc = new InternetAddress[destinationsCc.length];
        for (int i = 0; i < destinationsCc.length; i++) {
            addressCc[i] = new InternetAddress(destinationsCc[i]);
        }

        msg.setRecipients(Message.RecipientType.CC, addressCc);
    }

    String realdestinationBCc = destinationBCc;
    if (!Const.isEmpty(realdestinationBCc)) {
        // Split the mail-address BCc: space separated
        String[] destinationsBCc = realdestinationBCc.split(" ");
        InternetAddress[] addressBCc = new InternetAddress[destinationsBCc.length];
        for (int i = 0; i < destinationsBCc.length; i++) {
            addressBCc[i] = new InternetAddress(destinationsBCc[i]);
        }

        msg.setRecipients(Message.RecipientType.BCC, addressBCc);
    }

    if (mailsubject != null) {
        msg.setSubject(mailsubject);
    }

    msg.setSentDate(new Date());
    StringBuffer messageText = new StringBuffer();

    if (comment != null) {
        messageText.append(comment).append(Const.CR).append(Const.CR);
    }

    if (meta.getIncludeDate()) {
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.MsgDate") + ": ")
                .append(XMLHandler.date2string(new Date())).append(Const.CR).append(Const.CR);
    }

    if (!meta.isOnlySendComment() && (!Const.isEmpty(contactPerson) || !Const.isEmpty(contactPhone))) {
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.ContactInfo") + " :").append(Const.CR);
        messageText.append("---------------------").append(Const.CR);
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.PersonToContact") + " : ")
                .append(contactPerson).append(Const.CR);
        messageText.append(BaseMessages.getString(PKG, "Mail.Log.Comment.Tel") + "  : ").append(contactPhone)
                .append(Const.CR);
        messageText.append(Const.CR);
    }
    data.parts = new MimeMultipart();

    MimeBodyPart part1 = new MimeBodyPart(); // put the text in the
    // 1st part

    if (meta.isUseHTML()) {
        if (!Const.isEmpty(meta.getEncoding())) {
            part1.setContent(messageText.toString(), "text/html; " + "charset=" + meta.getEncoding());
        } else {
            part1.setContent(messageText.toString(), "text/html; " + "charset=ISO-8859-1");
        }
    } else {
        part1.setText(messageText.toString());
    }

    data.parts.addBodyPart(part1);

    if (meta.isAttachContentFromField()) {
        // attache file content
        addAttachedContent(data.previousRowMeta.getString(r, data.IndexOfAttachedFilename),
                data.previousRowMeta.getString(r, data.indexOfAttachedContent));
    } else {
        // attached files
        if (meta.isDynamicFilename()) {
            setAttachedFilesList(r, log);
        } else {
            setAttachedFilesList(null, log);
        }
    }

    // add embedded images
    addImagePart();

    if (data.nrEmbeddedImages > 0 && data.nrattachedFiles == 0) {
        // If we need to embedd images...
        // We need to create a "multipart/related" message.
        // otherwise image will appear as attached file
        data.parts.setSubType("related");
    }

    msg.setContent(data.parts);

    Transport transport = null;
    try {
        transport = session.getTransport(protocol);
        if (meta.isUsingAuthentication()) {
            if (port != -1) {
                transport.connect(Const.NVL(server, ""), port, Const.NVL(authenticationUser, ""),
                        Const.NVL(authenticationPassword, ""));
            } else {
                transport.connect(Const.NVL(server, ""), Const.NVL(authenticationUser, ""),
                        Const.NVL(authenticationPassword, ""));
            }
        } else {
            transport.connect();
        }
        transport.sendMessage(msg, msg.getAllRecipients());
    } finally {
        if (transport != null) {
            transport.close();
        }
    }

}

From source file:com.autentia.tnt.mail.DefaultMailService.java

public void sendOutputStreams(String to, String subject, String text, Map<InputStream, String> attachments)
        throws MessagingException {
    Transport t = null;

    try {//from  ww  w .j  a va2 s . co m
        MimeMessage message = new MimeMessage(session);

        t = session.getTransport("smtp");

        message.setFrom(new InternetAddress(configurationUtil.getMailUsername()));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setSubject(subject);
        message.setSentDate(new Date());
        if (attachments == null || attachments.size() < 1) {
            message.setText(text);
        } else {
            // create the message part 
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(text);
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            try {
                for (InputStream attachment : attachments.keySet()) {
                    messageBodyPart = new MimeBodyPart();
                    DataSource source = new ByteArrayDataSource(attachment, "application/octet-stream");

                    messageBodyPart.setDataHandler(new DataHandler(source));
                    messageBodyPart.setFileName(attachments.get(attachment)); //NOSONAR 
                    multipart.addBodyPart(messageBodyPart); //Se emplea keyset y no valueset porque se emplea tanto la key como el val
                }
            } catch (IOException e) {
                throw new MessagingException("cannot add an attachment to mail", e);
            }
            message.setContent(multipart);
        }

        t.connect(configurationUtil.getMailUsername(), configurationUtil.getMailPassword());

        t.sendMessage(message, message.getAllRecipients());
    } finally {
        if (t != null) {
            t.close();
        }
    }

}

From source file:org.sakaiproject.email.impl.BasicEmailService.java

protected void sendMessageAndLog(InternetAddress from, InternetAddress[] to, String subject,
        Map<RecipientType, InternetAddress[]> headerTo, long start, MimeMessage msg, Session session)
        throws MessagingException {
    long preSend = 0;
    if (M_log.isDebugEnabled())
        preSend = System.currentTimeMillis();

    if (allowTransport) {
        msg.saveChanges();/*  w  w  w  .j  ava 2 s  .  c  o m*/

        Transport transport = session.getTransport(protocol);

        if (m_smtpUser != null && m_smtpPassword != null)
            transport.connect(m_smtp, m_smtpUser, m_smtpPassword);
        else
            transport.connect();

        transport.sendMessage(msg, to);

        transport.close();
    }

    long end = 0;
    if (M_log.isDebugEnabled())
        end = System.currentTimeMillis();

    if (M_log.isInfoEnabled()) {
        StringBuilder buf = new StringBuilder();
        buf.append("Email.sendMail: from: ");
        buf.append(from);
        buf.append(" subject: ");
        buf.append(subject);
        buf.append(" to:");
        for (int i = 0; i < to.length; i++) {
            buf.append(" ");
            buf.append(to[i]);
        }
        if (headerTo != null) {
            if (headerTo.containsKey(RecipientType.TO)) {
                buf.append(" headerTo{to}:");
                InternetAddress[] headerToTo = headerTo.get(RecipientType.TO);
                for (int i = 0; i < headerToTo.length; i++) {
                    buf.append(" ");
                    buf.append(headerToTo[i]);
                }
            }
            if (headerTo.containsKey(RecipientType.CC)) {
                buf.append(" headerTo{cc}:");
                InternetAddress[] headerToCc = headerTo.get(RecipientType.CC);
                for (int i = 0; i < headerToCc.length; i++) {
                    buf.append(" ");
                    buf.append(headerToCc[i]);
                }
            }
            if (headerTo.containsKey(RecipientType.BCC)) {
                buf.append(" headerTo{bcc}:");
                InternetAddress[] headerToBcc = headerTo.get(RecipientType.BCC);
                for (int i = 0; i < headerToBcc.length; i++) {
                    buf.append(" ");
                    buf.append(headerToBcc[i]);
                }
            }
        }
        try {
            if (msg.getContent() instanceof Multipart) {
                Multipart parts = (Multipart) msg.getContent();
                buf.append(" with ").append(parts.getCount() - 1).append(" attachments");
            }
        } catch (IOException ioe) {
        }

        if (M_log.isDebugEnabled()) {
            buf.append(" time: ");
            buf.append("" + (end - start));
            buf.append(" in send: ");
            buf.append("" + (end - preSend));
        }

        M_log.info(buf.toString());
    }
}

From source file:com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController.java

public String[] notifyExternals(InfoLetterPublicationPdC ilp, String server, List<String> emails) {
    // Retrieve SMTP server information
    String host = getSmtpHost();//from  w w w. j a  v a2s  .  co  m
    boolean isSmtpAuthentication = isSmtpAuthentication();
    int smtpPort = getSmtpPort();
    String smtpUser = getSmtpUser();
    String smtpPwd = getSmtpPwd();
    boolean isSmtpDebug = isSmtpDebug();

    List<String> emailErrors = new ArrayList<String>();

    if (emails.size() > 0) {

        // Corps et sujet du message
        String subject = getString("infoLetter.emailSubject") + ilp.getName();
        // Email du publieur
        String from = getUserDetail().geteMail();
        // create some properties and get the default Session
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", String.valueOf(isSmtpAuthentication));

        Session session = Session.getInstance(props, null);
        session.setDebug(isSmtpDebug); // print on the console all SMTP messages.

        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "subject = " + subject);
        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "from = " + from);
        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "host= " + host);

        try {
            // create a message
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
            msg.setSubject(subject, CharEncoding.UTF_8);
            ForeignPK foreignKey = new ForeignPK(ilp.getPK().getId(), getComponentId());
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            List<SimpleDocument> contents = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.wysiwyg,
                            I18NHelper.defaultLanguage);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            for (SimpleDocument content : contents) {
                AttachmentServiceFactory.getAttachmentService().getBinaryContent(buffer, content.getPk(),
                        content.getLanguage());
            }
            mbp1.setDataHandler(
                    new DataHandler(new ByteArrayDataSource(
                            replaceFileServerWithLocal(
                                    IOUtils.toString(buffer.toByteArray(), CharEncoding.UTF_8), server),
                            MimeTypes.HTML_MIME_TYPE)));
            IOUtils.closeQuietly(buffer);
            // Fichiers joints
            WAPrimaryKey publiPK = ilp.getPK();
            publiPK.setComponentName(getComponentId());
            publiPK.setSpace(getSpaceId());

            // create the Multipart and its parts to it
            String mimeMultipart = getSettings().getString("SMTPMimeMultipart", "related");
            Multipart mp = new MimeMultipart(mimeMultipart);
            mp.addBodyPart(mbp1);

            // Images jointes
            List<SimpleDocument> fichiers = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.image, null);
            for (SimpleDocument attachment : fichiers) {
                // create the second message part
                MimeBodyPart mbp2 = new MimeBodyPart();

                // attach the file to the message
                FileDataSource fds = new FileDataSource(attachment.getAttachmentPath());
                mbp2.setDataHandler(new DataHandler(fds));
                // For Displaying images in the mail
                mbp2.setFileName(attachment.getFilename());
                mbp2.setHeader("Content-ID", attachment.getFilename());
                SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                        "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID());

                // create the Multipart and its parts to it
                mp.addBodyPart(mbp2);
            }

            // Fichiers joints
            fichiers = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.attachment, null);

            if (!fichiers.isEmpty()) {
                for (SimpleDocument attachment : fichiers) {
                    // create the second message part
                    MimeBodyPart mbp2 = new MimeBodyPart();

                    // attach the file to the message
                    FileDataSource fds = new FileDataSource(attachment.getAttachmentPath());
                    mbp2.setDataHandler(new DataHandler(fds));
                    mbp2.setFileName(attachment.getFilename());
                    // For Displaying images in the mail
                    mbp2.setHeader("Content-ID", attachment.getFilename());
                    SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                            "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID());

                    // create the Multipart and its parts to it
                    mp.addBodyPart(mbp2);
                }
            }

            // add the Multipart to the message
            msg.setContent(mp);
            // set the Date: header
            msg.setSentDate(new Date());
            // create a Transport connection (TCP)
            Transport transport = session.getTransport("smtp");

            InternetAddress[] address = new InternetAddress[1];
            for (String email : emails) {
                try {
                    address[0] = new InternetAddress(email);
                    msg.setRecipients(Message.RecipientType.TO, address);
                    // add Transport Listener to the transport connection.
                    if (isSmtpAuthentication) {
                        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                                "root.MSG_GEN_PARAM_VALUE",
                                "host = " + host + " m_Port=" + smtpPort + " m_User=" + smtpUser);
                        transport.connect(host, smtpPort, smtpUser, smtpPwd);
                        msg.saveChanges();
                    } else {
                        transport.connect();
                    }
                    transport.sendMessage(msg, address);
                } catch (Exception ex) {
                    SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()",
                            "root.MSG_GEN_PARAM_VALUE", "Email = " + email,
                            new InfoLetterException(
                                    "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController",
                                    SilverpeasRuntimeException.ERROR, ex.getMessage(), ex));
                    emailErrors.add(email);
                } finally {
                    if (transport != null) {
                        try {
                            transport.close();
                        } catch (Exception e) {
                            SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()",
                                    "root.EX_IGNORED", "ClosingTransport", e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new InfoLetterException(
                    "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController",
                    SilverpeasRuntimeException.ERROR, e.getMessage(), e);
        }
    }
    return emailErrors.toArray(new String[emailErrors.size()]);
}

From source file:org.sigmah.server.mail.MailSenderImpl.java

@Override
public void sendFile(Email email, String fileName, InputStream fileStream) throws EmailException {
    final String user = email.getAuthenticationUserName();
    final String password = email.getAuthenticationPassword();

    final Properties properties = new Properties();
    properties.setProperty(MAIL_TRANSPORT_PROTOCOL, TRANSPORT_PROTOCOL);
    properties.setProperty(MAIL_SMTP_HOST, email.getHostName());
    properties.setProperty(MAIL_SMTP_PORT, Integer.toString(email.getSmtpPort()));

    final StringBuilder toBuilder = new StringBuilder();
    for (final String to : email.getToAddresses()) {
        if (toBuilder.length() > 0) {
            toBuilder.append(',');
        }// w w w.  java2 s  . c  o  m
        toBuilder.append(to);
    }

    final StringBuilder ccBuilder = new StringBuilder();
    if (email.getCcAddresses().length > 0) {
        for (final String cc : email.getCcAddresses()) {
            if (ccBuilder.length() > 0) {
                ccBuilder.append(',');
            }
            ccBuilder.append(cc);
        }
    }

    final Session session = javax.mail.Session.getInstance(properties);
    try {
        final DataSource attachment = new ByteArrayDataSource(fileStream,
                FileType.fromExtension(FileType.getExtension(fileName), FileType._DEFAULT).getContentType());

        final Transport transport = session.getTransport();

        if (password != null) {
            transport.connect(user, password);
        } else {
            transport.connect();
        }

        final MimeMessage message = new MimeMessage(session);

        // Configures the headers.
        message.setFrom(new InternetAddress(email.getFromAddress(), false));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toBuilder.toString(), false));
        if (email.getCcAddresses().length > 0) {
            message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(ccBuilder.toString(), false));
        }

        message.setSubject(email.getSubject(), email.getEncoding());

        // Html body part.
        final MimeMultipart textMultipart = new MimeMultipart("alternative");

        final MimeBodyPart htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(email.getContent(), "text/html; charset=\"" + email.getEncoding() + "\"");
        textMultipart.addBodyPart(htmlBodyPart);

        final MimeBodyPart textBodyPart = new MimeBodyPart();
        textBodyPart.setContent(textMultipart);

        // Attachment body part.
        final MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.setDataHandler(new DataHandler(attachment));
        attachmentPart.setFileName(fileName);
        attachmentPart.setDescription(fileName);

        // Mail multipart content.
        final MimeMultipart contentMultipart = new MimeMultipart("related");
        contentMultipart.addBodyPart(textBodyPart);
        contentMultipart.addBodyPart(attachmentPart);

        message.setContent(contentMultipart);
        message.saveChanges();

        // Sends the mail.
        transport.sendMessage(message, message.getAllRecipients());

    } catch (UnsupportedEncodingException ex) {
        throw new EmailException(
                "An error occured while encoding the mail content to '" + email.getEncoding() + "'.", ex);

    } catch (IOException ex) {
        throw new EmailException("An error occured while reading the attachment of an email.", ex);

    } catch (MessagingException ex) {
        throw new EmailException("An error occured while sending an email.", ex);
    }
}

From source file:com.xpn.xwiki.plugin.mailsender.MailSenderPlugin.java

/**
 * Send a Collection of Mails (multiple emails)
 * /*from  w w  w . ja  va 2s .  co  m*/
 * @param emails Mail Collection
 * @return True in any case (TODO ?)
 */
public boolean sendMails(Collection<Mail> emails, MailConfiguration mailConfiguration, XWikiContext context)
        throws MessagingException, UnsupportedEncodingException {
    Session session = null;
    Transport transport = null;
    int emailCount = emails.size();
    int count = 0;
    int sendFailedCount = 0;
    try {
        for (Iterator<Mail> emailIt = emails.iterator(); emailIt.hasNext();) {
            count++;

            Mail mail = emailIt.next();
            LOGGER.info("Sending email: " + mail.toString());

            if ((transport == null) || (session == null)) {
                // initialize JavaMail Session and Transport
                Properties props = initProperties(mailConfiguration);
                session = Session.getInstance(props, null);
                transport = session.getTransport("smtp");
                if (!mailConfiguration.usesAuthentication()) {
                    // no auth info - typical 127.0.0.1 open relay scenario
                    transport.connect();
                } else {
                    // auth info present - typical with external smtp server
                    transport.connect(mailConfiguration.getSmtpUsername(), mailConfiguration.getSmtpPassword());
                }
            }

            try {
                MimeMessage message = createMimeMessage(mail, session, context);
                if (message == null) {
                    continue;
                }

                transport.sendMessage(message, message.getAllRecipients());

                // close the connection every other 100 emails
                if ((count % 100) == 0) {
                    try {
                        if (transport != null) {
                            transport.close();
                        }
                    } catch (MessagingException ex) {
                        LOGGER.error("MessagingException has occured.", ex);
                    }
                    transport = null;
                    session = null;
                }
            } catch (SendFailedException ex) {
                sendFailedCount++;
                LOGGER.error("SendFailedException has occured.", ex);
                LOGGER.error("Detailed email information" + mail.toString());
                if (emailCount == 1) {
                    throw ex;
                }
                if ((emailCount != 1) && (sendFailedCount > 10)) {
                    throw ex;
                }
            } catch (MessagingException mex) {
                LOGGER.error("MessagingException has occured.", mex);
                LOGGER.error("Detailed email information" + mail.toString());
                if (emailCount == 1) {
                    throw mex;
                }
            } catch (XWikiException e) {
                LOGGER.error("XWikiException has occured.", e);
            } catch (IOException e) {
                LOGGER.error("IOException has occured.", e);
            }
        }
    } finally {
        try {
            if (transport != null) {
                transport.close();
            }
        } catch (MessagingException ex) {
            LOGGER.error("MessagingException has occured.", ex);
        }

        LOGGER.info("sendEmails: Email count = " + emailCount + " sent count = " + count);
    }
    return true;
}