Java 邮件 API 未发送电子邮件

Java mail API is not sending emails

我有一个使用 Gmail SMTP 发送电子邮件的邮件服务 class,直到最近它一直在成功运行,同样 class 无法发送电子邮件而且我不知道'甚至在我调试或 运行 这段代码时看到任何错误消息。知道吗,发生了什么事?

public class MailService {

public static void sendEmail(String subject, String msgBody, String[] toEmails, 
        String[] ccEmails, String[] bccEmails,
        String fromEmail, String toName){

     Properties props = System.getProperties();
        props.put("mail.smtp.starttls.enable", true); // added this line
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.user", "mygmail-id");
        props.put("mail.smtp.password", "mypassword");
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", true);



        Session session = Session.getInstance(props,null);
    List<InternetAddress> toAdresses = null;
    List<InternetAddress> ccAdresses = null;
    List<InternetAddress> bccAdresses = null;
    try {
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(fromEmail));
        toAdresses = new ArrayList<InternetAddress>();
        ccAdresses = new ArrayList<InternetAddress>();
        bccAdresses = new ArrayList<InternetAddress>();
        for(String toEmail: toEmails){
            toAdresses.add(new InternetAddress(toEmail));
        }
        if(ccEmails != null && ccEmails.length > 0)
        for(String ccEmail: ccEmails){
            ccAdresses.add(new InternetAddress(ccEmail));
        }
        if(bccEmails != null && bccEmails.length > 0)
        for(String bccEmail: bccEmails){
            bccAdresses.add(new InternetAddress(bccEmail));
        }
        msg.addRecipients(Message.RecipientType.TO,
                toAdresses.toArray(new InternetAddress[toAdresses.size()]));
        msg.addRecipients(Message.RecipientType.CC,
                ccAdresses.toArray(new InternetAddress[ccAdresses.size()]));
        msg.addRecipients(Message.RecipientType.BCC,
                bccAdresses.toArray(new InternetAddress[bccAdresses.size()]));
        msg.setSubject(subject);
        msg.setContent(msgBody, "text/html");
        Transport.send(msg);

    } catch (AddressException e) {
        e.printStackTrace();
    } catch (MessagingException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
        // ...
    }
}

两件事:

正如@Bill Shannon 所建议的,您应该使用 Authenticator 而不是单独依赖 Properties:

Session session = Session.getInstance(props, new Authenticator() {

            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("my-gmail-id", "mypassword");
            }

        });

但即便如此 - Gmail 仍会因安全问题阻止您发送电子邮件,并提供 this link 以获取更多信息。