简体   繁体   English

发送电子邮件Java时的异常

[英]Exceptions while sending email Java

I am facing the problem with Exceptions while sending an email. 我在发送电子邮件时遇到异常问题。 Here is my code below 这是我的下面的代码

public static void sendEmail(String email, String subjectBody, String srcAndFile) throws Exception {
    System.out.println(srcAndFile);

    try {
        logger.debug("sending email to: " + email + "with attached file: " + srcAndFile);

        Properties props = System.getProperties();
        props.put("mail.smtp.host", address);
        props.put("mail.smtp.port", "25");
        props.put("mail.smtp.auth", "false");

        Session session_m = Session.getDefaultInstance(props, null);
        MimeMessage message = new MimeMessage(session_m);
        message.setFrom (new InternetAddress(sender, sender));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
        message.setSubject(subjectBody);
        message.setText("Hi");
        message.setHeader("Content-Type","text/plain;charset=windows-1251");

        Multipart multiPart = new MimeMultipart();
        MimeBodyPart messageText = new MimeBodyPart();
        messageText.setContent(subjectBody, "text/plain");
        multiPart.addBodyPart(messageText);

        MimeBodyPart rarAttachment = new MimeBodyPart();
        File f = new File(srcAndFile);
        FileDataSource rarFile = new FileDataSource(f);
        rarAttachment.setDataHandler(new DataHandler(rarFile));
        rarAttachment.setFileName(rarFile.getName());
        multiPart.addBodyPart(rarAttachment);

        message.setContent(multiPart);

        SMTPTransport t = (SMTPTransport)session_m.getTransport("smtp");
        t.connect(addrress, sender, null);
        t.sendMessage(message, message.getAllRecipients());
        success = true;

        } catch (AddressException e) {
            logger.error(e.getMessage());
            throw new AddressException("[sendEmail]: Incorrect email address");

        } catch (MessagingException e) {
            logger.error(e.getMessage());
            throw new MessagingException("[sendEmail]: Unable to send email");

        } catch (IOException e) {
            logger.error(e.getMessage());
            throw new IOException("[sendEmail]: Unable to find file to attach");

        } catch (Exception e) {
            logger.error(e.getMessage());
            DBWrapper.processStatusDB("[sendEmail]","failed",e.getMessage());
            throw  new Exception("[sendEmail]: Error in method " + e.getMessage());
        }
        DBWrapper.processStatusDB("[sendEmail]","finished","process to send an email with " + FileManager.getFile(srcAndFile) + " has finished properly");


}

Now the problem arises when I want to catch some errors: 现在,当我想捕获一些错误时,就会出现问题:

  1. Invalid address 无效地址

  2. Unable to connect to server 无法连接到服务器

Both of these cases are caught on (MessagingException e). 这两种情况都被捕获(MessagingException e)。 Is there a way to split them in different exceptions. 有没有一种方法可以将它们拆分为不同的异常。

The thing is that if email address of receiver is invalid, my program should continue with other recipients. 问题是,如果收件人的电子邮件地址无效,则我的程序应与其他收件人一起继续。 But if the program is unable to connect to mail server, then the program should terminate. 但是,如果该程序无法连接到邮件服务器,则该程序应终止。 But in my case it terminates even when email address is invalid. 但就我而言,即使电子邮件地址无效,它也会终止。 Since (MessagingException e) throws error as shown in the code. 由于(MessagingException e)会引发错误,如代码所示。

Is there any other exceptions to catch INVALID EMAIL ADDRESS? 是否还有其他例外可以捕获无效的电子邮件地址? (AddressException e) is not catching the error with invalid email. (AddressException e)无法使用无效的电子邮件捕获错误。

Thank you. 谢谢。

I feel, it is better to validate the mail address before trying to send the mail. 我认为,最好在尝试发送邮件之前先验证邮件地址。 This is something you know and can correct it even before the exception occurs. 这是您所知道的,即使在异常发生之前也可以纠正它。 Mail server not accessible is an exception which you can expect and thus make sense to catch it and do the post processing. 邮件服务器不可访问是您可以预料到的异常,因此有必要进行捕获并进行后期处理。

You could use the SendFailedException . 您可以使用SendFailedException An excerpt from the docs 文档摘录

This exception is thrown when the message cannot be sent. 无法发送消息时,抛出此异常。

The exception includes those addresses to which the message could not be sent as well as the valid addresses to which the message was sent and valid addresses to which the message was not sent. 例外包括无法将消息发送到的那些地址,以及消息已发送到的有效地址和消息未发送到的有效地址。

I was facing same problem a few days back. 几天前我遇到了同样的问题。 Try using 尝试使用

Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
          });

instead of 代替

Session session_m = Session.getDefaultInstance(props, null);

Also recheck your port number. 还要重新检查您的端口号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM