在Java API中处理退回的电子邮件

时间:2014-09-30 04:03:13

标签: java email javamail

我正在使用Java API发送批量电子邮件,我希望得到所有退回电子邮件的报告。阅读我发现我可以实施退回电子邮件地址:

  props.put("mail.smtp.from", bounceAddr);

但电子邮件总是被弹回原始地址。这是我的相关代码:

String smtpServer = "smtp.gmail.com";
    int port = 587;
    final String userid = "myuserid";//Source Email
    final String password = "mypassword";//Source Email
    String contentType = "text/html";
    String subject = "test: bounce an email to a different address "
            + "from the sender";
    String from = "mysourceaddress@gmail.com";
    String to = "myfakeaddress@gmail.com";//some invalid address
    String bounceAddr = "mybouncedEmailsaddress@gmail.com";//bounced Emails address
    String body = "Test: get message to bounce to a separate email address";

    Properties props = new Properties();

    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", smtpServer);
    props.put("mail.smtp.port", "587");
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.from", bounceAddr);
    Session mailSession = Session.getInstance(props,
            new javax.mail.Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(userid, password);
                }
            });

    MimeMessage message = new MimeMessage(mailSession);
    message.addFrom(InternetAddress.parse(from));
    message.setRecipients(Message.RecipientType.TO, to);
    message.setSubject(subject);
    message.setContent(body, contentType);

    Transport transport = mailSession.getTransport();
    try {
        System.out.println("Sending ....");
        transport.connect(smtpServer, port, userid, password);
        transport.sendMessage(message,
                message.getRecipients(Message.RecipientType.TO));
        System.out.println("Sending done ...");
    } catch (MessagingException e) {
        System.err.println("Error Sending: "  + e.getMessage());
    }
    transport.close();

电子邮件总是被弹回到mysourceaddress@gmail.com。我有什么遗失或有其他更好的方法来实现这个吗?

0 个答案:

没有答案