简体   繁体   中英

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). 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.

Is there any other exceptions to catch INVALID EMAIL ADDRESS? (AddressException e) is not catching the error with invalid email.

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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