使用javax.mail发送大型电子邮件,某些电子邮件的发送失败

时间:2017-08-24 06:56:15

标签: java email

我使用来自我的域名所拥有的SMTP服务器的javax.mail向用户发送了大量电子邮件(大约1000个)。并且所有收件人都在同一个域电子邮件中。

发送邮件时,如果只有成功,那么我将令牌保存在userToken表中。否则我没有将令牌保存在表中。完成该过程后,userToken表插入950行,这意味着所有电子邮件都成功。

我已经编写了以下代码来发送批量电子邮件,但是用户没有收到大约300封电子邮件。我执行时没有任何错误,

@RequestMapping(value = "bulkMail")
public  @ResponseBody  String bulkMail(Model model, HttpServletRequest request,@RequestParam(value="myArray") Long[] myArray, HttpServletResponse response) throws IOException {
    Session session = null;
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("roca");
    EntityManager entityManager = entityManagerFactory.createEntityManager();
    entityManager.getTransaction().begin();
    HttpSession httpSession = request.getSession(false);
    session = getRocaSession();
    Test test = (Test) httpSession.getAttribute("test");

    for (int i = 0; i < myArray.length; i++) {
        User user = entityManager.createQuery( "SELECT u FROM User u where u.userId=" + myArray[i], User.class).getSingleResult();

        UserToken userToken;
        try {
            userToken = entityManager.createQuery("SELECT ut FROM UserToken ut where ut.testId="+test.getId()+" and ut.userId="+myArray[i], UserToken.class).getSingleResult();
        } catch (Exception e) {
            userToken = new UserToken();
        }

        String mailStatus = sendMail(userToken,test,request, user.getUserId(),  user.getUserName(), context, user.getEmailId(),session);
        if (!mailStatus.equals("failure")) {
            userToken.setToken(mailStatus);
            userToken.setCreatedDate(new Date());
            userToken.setUpdatedDate(new Date());
            userToken.setTestId(test.getId());
            userToken.setUserId(user.getUserId());
            userToken.setUsed(0);
            testDao.saveOrUpdate(userToken);
        }
    }
    entityManager.getTransaction().commit();
    entityManager.close();
    return "Emails have been send to Users";
}

发送电子邮件

public String sendMail(UserTestToken userTestToken, Test test,HttpServletRequest request, Long accountId,String accountName,
        String context,String accountEmail,Session session) {
    String token = getToken();
    try {
        String email = mailService.sendAlert(test, accountEmail,"User Triger", "noreply@mydomain.com", "Val", accountId, token, context, accountName, session);
        if (!email.equals("failure")) {
            return token;
        }else {
            return "failure";
        }
    } catch (Exception e) {
        return "failure";
    }       
}

获取电子邮件的会话

public Session getSession() {
    Properties props = new Properties();
    props.put("mail.smtp.auth", "false");
    props.put("mail.smtp.host", "gatesmtp.moc.domain.com");
    props.put("mail.smtp.port", "25");
    Session session = Session.getInstance(props);
    session.setDebug(false);
    return session;
}

MailService Implementaion

public String sendTestMailAlert(Test test, String accountEmail, String receiverName, String senderEmail, String url, Long accountId, String token, String context, String       accountName, Session session)
{
    String subject = "Subject";
    String content = "Content";
    return sendMail(accountEmail, content, subject, receiverName, senderEmail, session);
}


private String sendMail(String receiverMailIds, String content, String subject, String employeeName, String employeeEmail, Session session) {
    try {
        Message message = new MimeMessage(session);
        try {
            message.setFrom(new InternetAddress(employeeEmail, employeeName));
        } catch (UnsupportedEncodingException e) {
            this.logger.error("Mail service address catch UnsupportedEncodingException");
        }
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiverMailIds));
        message.setSubject(subject);
        message.setContent(content, "text/html");
        Transport.send(message);
        return "success";
    } catch (Exception e) {
        this.logger.error("Mail Exception - " + receiverMailIds);
    }
    return "failure";
}

1 个答案:

答案 0 :(得分:0)

问题不在您的代码中:如果邮件在您的邮件服务器中正确排队,则问题出在最终收件人的SMTP服务器上。

当您的SMTP服务器(必须正确排入邮件的人)联系收件人SMTP服务器时,可能(当然......)收件人SMTP由于某些原因拒绝电子邮件(垃圾邮件?未知用户?邮件太多?邮箱已满?)。因此,您的SMTP服务器无法发送电子邮件,并尝试将其发送回发件人(您定义为“noreply@domain.com”)。如果此邮箱不存在,则SMTP服务器将删除邮件并(通常)仅在其内部日志上记录该操作。这就是为什么你不能注意到发生了什么。

您可以使用真正的发件人地址进行测试,而不是使用noreply。

玩得开心:)