Search in sources :

Example 51 with AddressException

use of javax.mail.internet.AddressException in project Asqatasun by Asqatasun.

the class EmailSender method sendEmail.

/**
 * @param emailFrom
 * @param emailToSet
 * @param emailBccSet (can be null)
 * @param replyTo (can be null)
 * @param emailSubject
 * @param emailContent
 */
public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo, String emailSubject, String emailContent) {
    // Set SMTP properties (host, port, ...)
    Properties props = new Properties();
    if (secureProtocolEnable) {
        smtpProtocol = "smtps";
        props.put("mail." + smtpProtocol + ".ssl.protocols", secureProtocols);
    } else if (startTtlsEnable) {
        smtpProtocol = "smtp";
        props.put("mail." + smtpProtocol + ".starttls.enable", "true");
        props.put("mail." + smtpProtocol + ".socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.put("mail." + smtpProtocol + ".socketFactory.fallback", "true");
        props.put("mail." + smtpProtocol + ".ssl.protocols", secureProtocols);
        if (smtpPort != -1) {
            props.put("mail." + smtpProtocol + ".socketFactory.port", smtpPort);
        }
    } else {
        smtpProtocol = "smtp";
        props.put("mail." + smtpProtocol + ".starttls.enable", "false");
    }
    props.put("mail." + smtpProtocol + ".host", smtpHost);
    props.put("mail." + smtpProtocol + ".auth", "true");
    if (smtpPort != -1) {
        props.put("mail." + smtpProtocol + ".port", smtpPort);
    }
    // Log SMTP configuration
    if (debug) {
        LOGGER.info("SMTP configuration: " + props.toString());
    }
    // create some properties and get the default Session
    Session session = Session.getInstance(props);
    session.setDebug(debug);
    try {
        Transport t = session.getTransport(smtpProtocol);
        t.connect(smtpHost, userName, password);
        // create a message
        MimeMessage msg = new MimeMessage(session);
        // set the from and to address
        InternetAddress addressFrom;
        try {
            // Used default from address is passed one is null or empty or
            // blank
            addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom) : new InternetAddress(from);
            msg.setFrom(addressFrom);
            Address[] recipients = new InternetAddress[emailToSet.size()];
            int i = 0;
            for (String emailTo : emailToSet) {
                recipients[i] = new InternetAddress(emailTo);
                i++;
            }
            msg.setRecipients(Message.RecipientType.TO, recipients);
            if (CollectionUtils.isNotEmpty(emailBccSet)) {
                Address[] bccRecipients = new InternetAddress[emailBccSet.size()];
                i = 0;
                for (String emailBcc : emailBccSet) {
                    bccRecipients[i] = new InternetAddress(emailBcc);
                    i++;
                }
                msg.setRecipients(Message.RecipientType.BCC, bccRecipients);
            }
            if (StringUtils.isNotBlank(replyTo)) {
                Address[] replyToRecipients = { new InternetAddress(replyTo) };
                msg.setReplyTo(replyToRecipients);
            }
            // Setting the Subject
            msg.setSubject(emailSubject, CHARSET_KEY);
            // Setting content and charset (warning: both declarations of
            // charset are needed)
            msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY);
            LOGGER.debug("emailContent  " + emailContent);
            msg.setContent(emailContent, FULL_CHARSET_KEY);
            try {
                LOGGER.debug("emailContent from message object " + msg.getContent().toString());
            } catch (IOException ex) {
                LOGGER.error(ex.getMessage());
            } catch (MessagingException ex) {
                LOGGER.error(ex.getMessage());
            }
            for (Address addr : msg.getAllRecipients()) {
                LOGGER.debug("addr " + addr);
            }
            t.sendMessage(msg, msg.getAllRecipients());
        } catch (AddressException ex) {
            LOGGER.warn("AddressException " + ex.getMessage());
            LOGGER.warn("AddressException " + ex.getStackTrace());
        }
    } catch (NoSuchProviderException e) {
        LOGGER.warn("NoSuchProviderException " + e.getMessage());
        LOGGER.warn("NoSuchProviderException " + e.getStackTrace());
    } catch (MessagingException e) {
        LOGGER.warn("MessagingException " + e.getMessage());
        LOGGER.warn("MessagingException " + e.getStackTrace());
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) InternetAddress(javax.mail.internet.InternetAddress) IOException(java.io.IOException) Properties(java.util.Properties) MimeMessage(javax.mail.internet.MimeMessage) AddressException(javax.mail.internet.AddressException)

Example 52 with AddressException

use of javax.mail.internet.AddressException in project jmeter by apache.

the class MailerVisualizer method actionPerformed.

// ////////////////////////////////////////////////////////////
// 
// Implementation of the ActionListener-Interface.
// 
// ////////////////////////////////////////////////////////////
/**
 * Reacts on an ActionEvent (like pressing a button).
 *
 * @param e
 *            The ActionEvent with information about the event and its
 *            source.
 */
@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == testerButton) {
        ResultCollector testElement = getModel();
        modifyTestElement(testElement);
        try {
            MailerModel model = ((MailerResultCollector) testElement).getMailerModel();
            model.sendTestMail();
            // $NON-NLS-1$
            displayMessage(JMeterUtils.getResString("mail_sent"), false);
        } catch (AddressException ex) {
            log.error("Invalid mail address ", ex);
            displayMessage(// $NON-NLS-1$
            JMeterUtils.getResString("invalid_mail_address") + "\n" + ex.getMessage(), // $NON-NLS-1$
            true);
        } catch (MessagingException ex) {
            log.error("Couldn't send mail...", ex);
            displayMessage(// $NON-NLS-1$
            JMeterUtils.getResString("invalid_mail") + "\n" + ex.getMessage(), // $NON-NLS-1$
            true);
        }
    }
}
Also used : MailerResultCollector(org.apache.jmeter.reporters.MailerResultCollector) MessagingException(javax.mail.MessagingException) AddressException(javax.mail.internet.AddressException) MailerModel(org.apache.jmeter.reporters.MailerModel) MailerResultCollector(org.apache.jmeter.reporters.MailerResultCollector) ResultCollector(org.apache.jmeter.reporters.ResultCollector)

Example 53 with AddressException

use of javax.mail.internet.AddressException in project hudson-2.x by hudson.

the class BaseMailSender method getMail.

/**
 * Returns prepared email.
 *
 * @return prepared email.
 * @throws MessagingException exception if any.
 */
protected MimeMessage getMail() throws MessagingException {
    MimeMessage msg = new HudsonMimeMessage(Mailer.descriptor().createSession());
    msg.setContent("", "text/plain");
    msg.setFrom(new InternetAddress(Mailer.descriptor().getAdminAddress()));
    msg.setSentDate(new Date());
    Set<InternetAddress> rcp = new LinkedHashSet<InternetAddress>();
    StringTokenizer tokens = new StringTokenizer(recipients);
    while (tokens.hasMoreTokens()) {
        String address = tokens.nextToken();
        try {
            rcp.add(new InternetAddress(address));
        } catch (AddressException ignore) {
        // ignore bad address, but try to send to other addresses
        }
    }
    msg.setRecipients(Message.RecipientType.TO, rcp.toArray(new InternetAddress[rcp.size()]));
    msg.setSubject(new StringBuilder().append(getSubjectPrefix()).append(" ").append(getSubject()).toString(), charset);
    msg.setText(new StringBuilder().append(getText()).append(getTextFooter()).toString(), charset);
    return msg;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) InternetAddress(javax.mail.internet.InternetAddress) StringTokenizer(java.util.StringTokenizer) HudsonMimeMessage(hudson.tasks.HudsonMimeMessage) MimeMessage(javax.mail.internet.MimeMessage) AddressException(javax.mail.internet.AddressException) HudsonMimeMessage(hudson.tasks.HudsonMimeMessage) Date(java.util.Date)

Example 54 with AddressException

use of javax.mail.internet.AddressException in project wechat by dllwh.

the class SendMailHelper method sendHtmlMail.

/**
 * @Description:发送HTML格式的邮件
 * @param EmailInfo
 * @return
 * @throws MessagingException
 * @throws AddressException
 * @return:boolean 返回类型
 */
public boolean sendHtmlMail(EmailInfo emailInfo) {
    try {
        // 创建一个 Message,请将 Session 对象传递给 MimeMessage 构造器
        msg = new MimeMessage(session);
        // 设置发件人
        msg.setFrom(new InternetAddress(emailInfo.getFromAddress()));
        // 设置收件人
        msg.addRecipients(RecipientType.TO, emailInfo.getToAddress());
        // 设置主题
        msg.setSubject(emailInfo.getSubject());
        // 创建一个部件
        MimeBodyPart part = new MimeBodyPart();
        // 设置邮件文本内容
        part.setContent(emailInfo.getContent(), "text/html;charset=utf-8");
        // 保存邮件
        msg.saveChanges();
        Transport.send(msg);
        return true;
    } catch (Exception sExp) {
        sExp.printStackTrace();
        return false;
    }
}
Also used : InternetAddress(javax.mail.internet.InternetAddress) MimeMessage(javax.mail.internet.MimeMessage) MimeBodyPart(javax.mail.internet.MimeBodyPart) AddressException(javax.mail.internet.AddressException) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException)

Example 55 with AddressException

use of javax.mail.internet.AddressException in project openolat by klemens.

the class MailManagerImpl method createMimeMessage.

@Override
public MimeMessage createMimeMessage(Address from, Address[] tos, Address[] ccs, Address[] bccs, String subject, String body, List<File> attachments, MailerResult result) {
    if (from == null || ((tos == null || tos.length == 0) && ((ccs == null || ccs.length == 0)) && (bccs == null || bccs.length == 0)))
        return null;
    try {
        MimeMessage msg = createMessage(subject, from);
        if (tos != null && tos.length > 0) {
            msg.addRecipients(RecipientType.TO, tos);
        }
        if (ccs != null && ccs.length > 0) {
            msg.addRecipients(RecipientType.CC, ccs);
        }
        if (bccs != null && bccs.length > 0) {
            msg.addRecipients(RecipientType.BCC, bccs);
        }
        if (attachments != null && !attachments.isEmpty()) {
            // with attachment use multipart message
            Multipart multipart = new MimeMultipart("mixed");
            // 1) add body part
            if (StringHelper.isHtml(body)) {
                Multipart alternativePart = createMultipartAlternative(body);
                MimeBodyPart wrap = new MimeBodyPart();
                wrap.setContent(alternativePart);
                multipart.addBodyPart(wrap);
            } else {
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setText(body);
                multipart.addBodyPart(messageBodyPart);
            }
            // 2) add attachments
            for (File attachmentFile : attachments) {
                // abort if attachment does not exist
                if (attachmentFile == null || !attachmentFile.exists()) {
                    result.setReturnCode(MailerResult.ATTACHMENT_INVALID);
                    log.error("Tried to send mail wit attachment that does not exist::" + (attachmentFile == null ? null : attachmentFile.getAbsolutePath()), null);
                    return msg;
                }
                BodyPart filePart = new MimeBodyPart();
                DataSource source = new FileDataSource(attachmentFile);
                filePart.setDataHandler(new DataHandler(source));
                filePart.setFileName(attachmentFile.getName());
                multipart.addBodyPart(filePart);
            }
            // Put parts in message
            msg.setContent(multipart);
        } else {
            // without attachment everything is easy, just set as text
            if (StringHelper.isHtml(body)) {
                msg.setContent(createMultipartAlternative(body));
            } else {
                msg.setText(body, "utf-8");
            }
        }
        msg.setSentDate(new Date());
        msg.saveChanges();
        return msg;
    } catch (AddressException e) {
        result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
        log.error("", e);
        return null;
    } catch (MessagingException e) {
        result.setReturnCode(MailerResult.SEND_GENERAL_ERROR);
        log.error("", e);
        return null;
    } catch (UnsupportedEncodingException e) {
        result.setReturnCode(MailerResult.SENDER_ADDRESS_ERROR);
        log.error("", e);
        return null;
    }
}
Also used : BodyPart(javax.mail.BodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart) MimeMultipart(javax.mail.internet.MimeMultipart) Multipart(javax.mail.Multipart) MessagingException(javax.mail.MessagingException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DataHandler(javax.activation.DataHandler) Date(java.util.Date) FileDataSource(javax.activation.FileDataSource) DataSource(javax.activation.DataSource) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) AddressException(javax.mail.internet.AddressException) FileDataSource(javax.activation.FileDataSource) MimeBodyPart(javax.mail.internet.MimeBodyPart) File(java.io.File)

Aggregations

AddressException (javax.mail.internet.AddressException)130 InternetAddress (javax.mail.internet.InternetAddress)108 MimeMessage (javax.mail.internet.MimeMessage)43 MessagingException (javax.mail.MessagingException)38 ArrayList (java.util.ArrayList)23 IOException (java.io.IOException)21 UnsupportedEncodingException (java.io.UnsupportedEncodingException)21 Address (javax.mail.Address)21 JavaMailInternetAddress (com.zimbra.common.mime.shim.JavaMailInternetAddress)18 Properties (java.util.Properties)18 Session (javax.mail.Session)15 Date (java.util.Date)14 MimeBodyPart (javax.mail.internet.MimeBodyPart)14 MimeMultipart (javax.mail.internet.MimeMultipart)12 File (java.io.File)11 Message (javax.mail.Message)10 Multipart (javax.mail.Multipart)9 DataHandler (javax.activation.DataHandler)8 Test (org.junit.Test)7 ZMimeMessage (com.zimbra.common.zmime.ZMimeMessage)5