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:com.github.thorqin.toolkit.mail.MailService.java

private void sendMail(Mail mail) {
    long beginTime = System.currentTimeMillis();
    Properties props = new Properties();
    final Session session;
    props.put("mail.smtp.auth", String.valueOf(setting.auth));
    // If want to display SMTP protocol detail then uncomment following statement
    // props.put("mail.debug", "true");
    props.put("mail.smtp.host", setting.host);
    props.put("mail.smtp.port", setting.port);
    if (setting.secure.equals(SECURE_STARTTLS)) {
        props.put("mail.smtp.starttls.enable", "true");

    } else if (setting.secure.equals(SECURE_SSL)) {
        props.put("mail.smtp.socketFactory.port", setting.port);
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
    }//from w  w w . j ava2s .  co  m
    if (!setting.auth)
        session = Session.getInstance(props);
    else
        session = Session.getInstance(props, new javax.mail.Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(setting.user, setting.password);
            }
        });

    if (setting.debug)
        session.setDebug(true);

    MimeMessage message = new MimeMessage(session);
    StringBuilder mailTo = new StringBuilder();
    try {
        if (mail.from != null)
            message.setFrom(new InternetAddress(mail.from));
        else if (setting.from != null)
            message.setFrom(new InternetAddress(setting.from));
        if (mail.to != null) {
            for (String to : mail.to) {
                if (mailTo.length() > 0)
                    mailTo.append(",");
                mailTo.append(to);
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }
        }
        if (mail.subject != null)
            message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?=");
        message.setSentDate(new Date());

        BodyPart bodyPart = new MimeBodyPart();
        if (mail.htmlBody != null)
            bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8");
        else if (mail.textBody != null)
            bodyPart.setText(mail.textBody);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);

        if (mail.attachments != null) {
            for (String attachment : mail.attachments) {
                BodyPart attachedBody = new MimeBodyPart();
                File attachedFile = new File(attachment);
                DataSource source = new FileDataSource(attachedFile);
                attachedBody.setDataHandler(new DataHandler(source));
                attachedBody.setDisposition(MimeBodyPart.ATTACHMENT);
                String filename = attachedFile.getName();
                attachedBody.setFileName(
                        "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?=");
                multipart.addBodyPart(attachedBody);
            }
        }

        message.setContent(multipart);
        message.saveChanges();
        Transport transport = session.getTransport("smtp");
        transport.connect();

        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        if (setting.trace && tracer != null) {
            Tracer.Info info = new Tracer.Info();
            info.catalog = "mail";
            info.name = "send";
            info.put("sender", StringUtils.join(message.getFrom()));
            info.put("recipients", mail.to);
            info.put("SMTPServer", setting.host);
            info.put("SMTPAccount", setting.user);
            info.put("subject", mail.subject);
            info.put("startTime", beginTime);
            info.put("runningTime", System.currentTimeMillis() - beginTime);
            tracer.trace(info);
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Send mail failed!", ex);
    }
}

From source file:com.github.thorqin.webapi.mail.MailService.java

private void doSendMail(Mail mail) {
    long beginTime = System.currentTimeMillis();
    Properties props = new Properties();
    Session session;/*from  ww  w .  j  a  v  a2  s .co  m*/
    props.put("mail.smtp.auth", String.valueOf(serverConfig.useAuthentication()));
    // If want to display SMTP protocol detail then uncomment following statement
    // props.put("mail.debug", "true");
    props.put("mail.smtp.host", serverConfig.getHost());
    if (serverConfig.getPort() != null) {
        props.put("mail.smtp.port", serverConfig.getPort());
    }
    if (serverConfig.getSecure().equals(MailConfig.SECURE_STARTTLS)) {
        props.put("mail.smtp.starttls.enable", "true");
        if (!serverConfig.useAuthentication())
            session = Session.getInstance(props);
        else
            session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword());
                }
            });
    } else if (serverConfig.getSecure().equals(MailConfig.SECURE_SSL)) {
        props.put("mail.smtp.socketFactory.port", serverConfig.getPort());
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        if (!serverConfig.useAuthentication())
            session = Session.getInstance(props);
        else
            session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword());
                }
            });
    } else {
        if (!serverConfig.useAuthentication())
            session = Session.getInstance(props);
        else
            session = Session.getInstance(props, new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(serverConfig.getUsername(), serverConfig.getPassword());
                }
            });
    }

    // Uncomment to show SMTP protocal
    // session.setDebug(true);

    MimeMessage message = new MimeMessage(session);
    StringBuilder mailTo = new StringBuilder();
    try {
        if (mail.from != null)
            message.setFrom(new InternetAddress(mail.from));
        else if (serverConfig.getFrom() != null)
            message.setFrom(new InternetAddress(serverConfig.getFrom()));
        if (mail.to != null) {
            for (String to : mail.to) {
                if (mailTo.length() > 0)
                    mailTo.append(",");
                mailTo.append(to);
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            }
        }
        if (mail.subject != null)
            message.setSubject("=?UTF-8?B?" + Base64.encodeBase64String(mail.subject.getBytes("utf-8")) + "?=");
        message.setSentDate(new Date());

        BodyPart bodyPart = new MimeBodyPart();
        if (mail.htmlBody != null)
            bodyPart.setContent(mail.htmlBody, "text/html;charset=utf-8");
        else if (mail.textBody != null)
            bodyPart.setText(mail.textBody);
        Multipart multipart = new MimeMultipart();
        multipart.addBodyPart(bodyPart);

        if (mail.attachments != null) {
            for (String attachment : mail.attachments) {
                BodyPart attachedBody = new MimeBodyPart();
                File attachedFile = new File(attachment);
                DataSource source = new FileDataSource(attachedFile);
                attachedBody.setDataHandler(new DataHandler(source));
                attachedBody.setDisposition(MimeBodyPart.ATTACHMENT);
                String filename = attachedFile.getName();
                attachedBody.setFileName(
                        "=?UTF-8?B?" + Base64.encodeBase64String(filename.getBytes("utf-8")) + "?=");
                multipart.addBodyPart(attachedBody);
            }
        }

        message.setContent(multipart);
        message.saveChanges();
        Transport transport = session.getTransport("smtp");
        transport.connect();

        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        if (serverConfig.enableTrace()) {
            MailInfo info = new MailInfo();
            info.recipients = mail.to;
            info.sender = StringUtil.join(message.getFrom());
            info.smtpServer = serverConfig.getHost();
            info.smtpUser = serverConfig.getUsername();
            info.subject = mail.subject;
            info.startTime = beginTime;
            info.runningTime = System.currentTimeMillis() - beginTime;
            MonitorService.record(info);
        }
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Send mail failed!", ex);
    }
}

From source file:org.opencastproject.kernel.mail.SmtpService.java

/**
 * Sends <code>message</code> using the configured transport.
 * /*  w w  w  .  j av a  2s.  c om*/
 * @param message
 *          the message
 * @throws MessagingException
 *           if sending the message failed
 */
public void send(MimeMessage message) throws MessagingException {
    Transport t = getSession().getTransport(mailTransport);
    try {
        if (mailUser != null)
            t.connect(mailUser, mailPassword);
        else
            t.connect();
        t.sendMessage(message, message.getAllRecipients());
    } finally {
        t.close();
    }
}

From source file:be.fedict.eid.pkira.blm.model.mail.MailHandlerBean.java

@Override
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void onMessage(Message arg0) {
    ObjectMessage objectMessage = (ObjectMessage) arg0;
    try {//from  w  w w .jav a2s  .co  m
        Mail mail = (Mail) objectMessage.getObject();

        // Get properties
        String mailProtocol = getMailProtocol();
        String mailServer = getSmtpServer();
        String mailUser = getSmtpUser();
        String mailPort = getSmtpPort();
        String mailPassword = getSmtpPassword();

        // Initialize a mail session
        Properties props = new Properties();
        props.put("mail." + mailProtocol + ".host", mailServer);
        props.put("mail." + mailProtocol + ".port", mailPort);
        Session session = Session.getInstance(props);

        // Create the message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(mail.getSender()));
        for (String recipient : mail.getRecipients()) {
            msg.addRecipient(RecipientType.TO, new InternetAddress(recipient));
        }
        msg.setSubject(mail.getSubject(), "UTF-8");

        Multipart multipart = new MimeMultipart();
        msg.setContent(multipart);

        // Set the email message text and attachment
        MimeBodyPart messagePart = new MimeBodyPart();
        messagePart.setContent(mail.getBody(), mail.getContentType());
        multipart.addBodyPart(messagePart);

        if (mail.getAttachmentData() != null) {
            ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(mail.getAttachmentData(),
                    mail.getAttachmentContentType());
            DataHandler dataHandler = new DataHandler(byteArrayDataSource);
            MimeBodyPart attachmentPart = new MimeBodyPart();
            attachmentPart.setDataHandler(dataHandler);
            attachmentPart.setFileName(mail.getAttachmentFileName());

            multipart.addBodyPart(attachmentPart);
        }

        // Open transport and send message
        Transport transport = session.getTransport(mailProtocol);
        if (StringUtils.isNotBlank(mailUser)) {
            transport.connect(mailUser, mailPassword);
        } else {
            transport.connect();
        }
        msg.saveChanges();
        transport.sendMessage(msg, msg.getAllRecipients());
    } catch (JMSException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot handle the object message from the queue", e);
        throw new RuntimeException(e);
    } catch (MessagingException e) {
        errorLogger.logError(ApplicationComponent.MAIL, "Cannot send a mail message", e);
        throw new RuntimeException(e);
    }
}

From source file:ch.entwine.weblounge.kernel.mail.SmtpService.java

/**
 * Sends <code>message</code> using the configured transport.
 * /*w  w  w  .j  a  va2s. c om*/
 * @param message
 *          the message
 * @throws MessagingException
 *           if sending the message failed
 */
public void send(MimeMessage message) throws MessagingException {
    Transport t = getSession().getTransport(MAIL_TRANSPORT);
    try {
        if (mailUser != null)
            t.connect(mailUser, mailPassword);
        else
            t.connect();
        t.sendMessage(message, message.getAllRecipients());
    } finally {
        t.close();
    }
}

From source file:com.ilopez.jasperemail.JasperEmail.java

public void emailReport(String emailHost, final String emailUser, final String emailPass,
        Set<String> emailRecipients, String emailSender, String emailSubject, List<String> attachmentFileNames,
        Boolean smtpauth, OptionValues.SMTPType smtpenc, Integer smtpport) throws MessagingException {

    Logger.getLogger(JasperEmail.class.getName()).log(Level.INFO, emailHost + " " + emailUser + " " + emailPass
            + " " + emailSender + " " + emailSubject + " " + smtpauth + " " + smtpenc + " " + smtpport);
    Properties props = new Properties();

    // Setup Email Settings
    props.setProperty("mail.smtp.host", emailHost);
    props.setProperty("mail.smtp.port", smtpport.toString());
    props.setProperty("mail.smtp.auth", smtpauth.toString());

    if (smtpenc == OptionValues.SMTPType.SSL) {
        // SSL settings
        props.put("mail.smtp.socketFactory.port", smtpport.toString());
        props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
    } else if (smtpenc == OptionValues.SMTPType.TLS) {
        // TLS Settings
        props.put("mail.smtp.starttls.enable", "true");
    } else {/*from w  w w  .  j  a v  a 2s  . c o m*/
        // Plain
    }

    // Setup and Apply the Email Authentication

    Session mailSession = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(emailUser, emailPass);
        }
    });

    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject(emailSubject);
    for (String emailRecipient : emailRecipients) {
        Address toAddress = new InternetAddress(emailRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);
    }
    Address fromAddress = new InternetAddress(emailSender);
    message.setFrom(fromAddress);
    // Message text
    Multipart multipart = new MimeMultipart();
    BodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText("Database report attached\n\n");
    multipart.addBodyPart(textBodyPart);
    // Attachments
    for (String attachmentFileName : attachmentFileNames) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentFileName);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", "");
        fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", "");
        attachmentBodyPart.setFileName(fileNameWithoutPath);
        multipart.addBodyPart(attachmentBodyPart);
    }
    // add parts to message
    message.setContent(multipart);
    // send via SMTP
    Transport transport = mailSession.getTransport("smtp");

    transport.connect();
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}

From source file:org.artifactory.mail.MailServiceImpl.java

/**
 * Send an e-mail message//from w ww. j a  va  2 s  .co  m
 *
 * @param recipients Recipients of the message that will be sent
 * @param subject    The subject of the message
 * @param body       The body of the message
 * @param config     A mail server configuration to use
 * @throws Exception
 */
@Override
public void sendMail(String[] recipients, String subject, String body, final MailServerConfiguration config)
        throws EmailException {

    verifyParameters(recipients, config);

    if (!config.isEnabled()) {
        log.debug("Ignoring requested mail delivery. The given configuration is disabled.");
        return;
    }

    boolean debugEnabled = log.isDebugEnabled();

    Properties properties = new Properties();

    properties.put("mail.smtp.host", config.getHost());
    properties.put("mail.smtp.port", Integer.toString(config.getPort()));

    properties.put("mail.smtp.quitwait", "false");

    //Default protocol
    String protocol = "smtp";

    //Enable TLS if set
    if (config.isUseTls()) {
        properties.put("mail.smtp.starttls.enable", "true");
    }

    //Enable SSL if set
    boolean useSsl = config.isUseSsl();
    if (useSsl) {
        properties.put("mail.smtp.socketFactory.port", Integer.toString(config.getPort()));
        properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.put("mail.smtp.socketFactory.fallback", "false");
        //Requires special protocol
        protocol = "smtps";
    }

    //Set debug property if enabled by the logger
    properties.put("mail.debug", debugEnabled);

    Authenticator authenticator = null;
    if (!StringUtils.isEmpty(config.getUsername())) {
        properties.put("mail.smtp.auth", "true");
        authenticator = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(config.getUsername(), config.getPassword());
            }
        };
    }

    Session session = Session.getInstance(properties, authenticator);
    Message message = new MimeMessage(session);

    String subjectPrefix = config.getSubjectPrefix();
    String fullSubject = (!StringUtils.isEmpty(subjectPrefix)) ? (subjectPrefix + " " + subject) : subject;
    try {
        message.setSubject(fullSubject);

        if (!StringUtils.isEmpty(config.getFrom())) {
            InternetAddress addressFrom = new InternetAddress(config.getFrom());
            message.setFrom(addressFrom);
        }

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

        //Create multi-part message in case we want to add html support
        Multipart multipart = new MimeMultipart("related");

        BodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(body, "text/html");
        multipart.addBodyPart(htmlPart);
        message.setContent(multipart);

        //Set debug property if enabled by the logger
        session.setDebug(debugEnabled);

        //Connect and send
        Transport transport = session.getTransport(protocol);
        if (useSsl) {
            transport.connect(config.getHost(), config.getPort(), config.getUsername(), config.getPassword());
        } else {
            transport.connect();
        }
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
    } catch (MessagingException e) {
        String em = e.getMessage();
        throw new EmailException(
                "An error has occurred while sending an e-mail" + (em != null ? ": " + em.trim() : "") + ".\n",
                e);
    }
}

From source file:com.gtwm.jasperexecute.RunJasperReports.java

public void emailReport(String emailHost, String emailUser, String emailPass, Set<String> emailRecipients,
        String emailSender, String emailSubject, List<String> attachmentFileNames) throws MessagingException {
    Properties props = new Properties();
    //props.setProperty("mail.debug", "true");
    props.setProperty("mail.smtp.host", emailHost);
    if (emailUser != null) {
        props.setProperty("mail.smtp.auth", "true");
    }//from   w ww .j  a va2  s  .  c o m
    Authenticator emailAuthenticator = new EmailAuthenticator(emailUser, emailPass);
    Session mailSession = Session.getDefaultInstance(props, emailAuthenticator);
    MimeMessage message = new MimeMessage(mailSession);
    message.setSubject(emailSubject);
    for (String emailRecipient : emailRecipients) {
        Address toAddress = new InternetAddress(emailRecipient);
        message.addRecipient(Message.RecipientType.TO, toAddress);
    }
    Address fromAddress = new InternetAddress(emailSender);
    message.setFrom(fromAddress);
    // Message text
    Multipart multipart = new MimeMultipart();
    BodyPart textBodyPart = new MimeBodyPart();
    textBodyPart.setText("Database report attached\n\n");
    multipart.addBodyPart(textBodyPart);
    // Attachments
    for (String attachmentFileName : attachmentFileNames) {
        BodyPart attachmentBodyPart = new MimeBodyPart();
        DataSource source = new FileDataSource(attachmentFileName);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        String fileNameWithoutPath = attachmentFileName.replaceAll("^.*\\/", "");
        fileNameWithoutPath = fileNameWithoutPath.replaceAll("^.*\\\\", "");
        attachmentBodyPart.setFileName(fileNameWithoutPath);
        multipart.addBodyPart(attachmentBodyPart);
    }
    // add parts to message
    message.setContent(multipart);
    // send via SMTP
    Transport transport = mailSession.getTransport("smtp");
    // transport.connect(emailHost, emailUser, emailPass);
    transport.connect();
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();
}

From source file:mx.uatx.tesis.managebeans.IndexMB.java

public void enviarCorreo(String nombre, String apellido, String corre, String password2) throws Exception {
    try {//from  w  w w.  ja  v a2 s. c o  m
        // Propiedades de la conexin
        Properties props = new Properties();
        props.setProperty("mail.smtp.host", "smtp.gmail.com");
        props.setProperty("mail.smtp.starttls.enable", "true");
        props.setProperty("mail.smtp.port", "587");
        props.setProperty("mail.smtp.user", "alfons018pbg@gmail.com");
        props.setProperty("mail.smtp.auth", "true");

        // Preparamos la sesion
        Session session = Session.getDefaultInstance(props);

        // Construimos el mensaje
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("alfons018pbg@gmail.com"));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress("" + corre + ""));
        message.setSubject("Asistencia tcnica");
        message.setText("\n \n \n Estimado:  " + nombre + "  " + apellido
                + "\n El Servicio Tecnico de SEA ta da la bienvenida. "
                + "\n Los siguientes son tus datos para acceder:" + "\n Correo:    " + corre + "\n Password: "
                + password2 + "");

        // Lo enviamos.
        Transport t = session.getTransport("smtp");
        t.connect("alfons018pbg@gmail.com", "al12fo05zo1990");
        t.sendMessage(message, message.getAllRecipients());

        // Cierre.
        t.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.sakaiproject.tool.assessment.util.SamigoEmailService.java

public String sendMail() {
    try {/*  ww  w.j  av a  2  s. c  o m*/
        Properties props = new Properties();

        // Server
        if (smtpServer == null || smtpServer.equals("")) {
            log.info("samigo.email.smtpServer is not set");
            smtpServer = ServerConfigurationService.getString("smtp@org.sakaiproject.email.api.EmailService");
            if (smtpServer == null || smtpServer.equals("")) {
                log.info("smtp@org.sakaiproject.email.api.EmailService is not set");
                log.error(
                        "Please set the value of samigo.email.smtpServer or smtp@org.sakaiproject.email.api.EmailService");
                return "error";
            }
        }
        props.setProperty("mail.smtp.host", smtpServer);

        // Port
        if (smtpPort == null || smtpPort.equals("")) {
            log.warn("samigo.email.smtpPort is not set. The default port 25 will be used.");
        } else {
            props.setProperty("mail.smtp.port", smtpPort);
        }

        props.put("mail.smtp.sendpartial", "true");

        Session session = Session.getInstance(props, null);
        session.setDebug(true);
        MimeMessage msg = new MimeMessage(session);

        InternetAddress fromIA = new InternetAddress(fromEmailAddress, fromName);
        msg.setFrom(fromIA);

        //msg.addHeaderLine("Subject: " + subject);
        msg.setSubject(subject, "UTF-8");
        String noReplyEmaillAddress = ServerConfigurationService.getString("setup.request",
                "no-reply@" + ServerConfigurationService.getServerName());
        msg.addHeaderLine("To: " + noReplyEmaillAddress);
        msg.setText(message, "UTF-8");
        msg.addHeaderLine("Content-Type: text/html");

        ArrayList<InternetAddress> toIAList = new ArrayList<InternetAddress>();
        String email = "";
        Iterator iter = toEmailAddressList.iterator();
        while (iter.hasNext()) {
            try {
                email = (String) iter.next();
                toIAList.add(new InternetAddress(email));
            } catch (AddressException ae) {
                log.error("invalid email address: " + email);
            }
        }

        InternetAddress[] toIA = new InternetAddress[toIAList.size()];
        int count = 0;
        Iterator iter2 = toIAList.iterator();
        while (iter2.hasNext()) {
            toIA[count++] = (InternetAddress) iter2.next();
        }

        try {
            Transport transport = session.getTransport("smtp");
            msg.saveChanges();
            transport.connect();

            try {
                transport.sendMessage(msg, toIA);
            } catch (SendFailedException e) {
                log.debug("SendFailedException: " + e);
                return "error";
            } catch (MessagingException e) {
                log.warn("1st MessagingException: " + e);
                return "error";
            }
            transport.close();
        } catch (MessagingException e) {
            log.warn("2nd MessagingException:" + e);
            return "error";
        }

    } catch (UnsupportedEncodingException ue) {
        log.warn("UnsupportedEncodingException:" + ue);
        ue.printStackTrace();

    } catch (MessagingException me) {
        log.warn("3rd MessagingException:" + me);
        return "error";
    }
    return "send";
}