使用java通过gmail发送电子邮件

Mai*_*aik 4 java gmail

正如标题所示,我想用我的 gmail 帐户发送电子邮件,编写一些 java 代码。我找到了很多代码示例,但没有一个对我有用

我正在寻找这个:How can I send an email by Java application using GMail, Yahoo, or Hotmail?

我已经尝试过作为答案发布的代码,但我得到了这个异常:

javax.mail.MessagingException: Can't send command to SMTP host;
  nested exception is:
    javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
    at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1717)
    at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:1704)
    at com.sun.mail.smtp.SMTPTransport.ehlo(SMTPTransport.java:1088)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:468)
    at javax.mail.Service.connect(Service.java:291)
    at javax.mail.Service.connect(Service.java:172)
...
Run Code Online (Sandbox Code Playgroud)

代码是这样的:

public class GmailTest {
   
    private static String USER_NAME = "*****";  // GMail user name (just the part before "@gmail.com")
    private static String PASSWORD = "********"; // GMail password
    private static String RECIPIENT = "random.address@gmail.com";

    public static void main(String[] args) {
        String from = USER_NAME;
        String pass = PASSWORD;
        String[] to = { RECIPIENT }; // list of recipient email addresses
        String subject = "Java send mail example";
        String body = "Welcome to JavaMail!";

        sendFromGMail(from, pass, to, subject, body);
    }

    private static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
        Properties props = System.getProperties();
        String host = "smtp.gmail.com";
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);
        MimeMessage message = new MimeMessage(session);

        try {
            message.setFrom(new InternetAddress(from));
            InternetAddress[] toAddress = new InternetAddress[to.length];

            // To get the array of addresses
            for( int i = 0; i < to.length; i++ ) {
                toAddress[i] = new InternetAddress(to[i]);
            }

            for( int i = 0; i < toAddress.length; i++) {
                message.addRecipient(Message.RecipientType.TO, toAddress[i]);
            }

            message.setSubject(subject);
            message.setText(body);
            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, pass);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这应该在 2022 年发挥作用还是发生了一些变化?为什么我会得到这个例外?

hid*_*ine 5

    public class EmailService {

    private String username;
    private String password;

    private final Properties prop;
public EmailService(String host, int port, String username, String password) {
            prop = new Properties();
            prop.put("mail.smtp.auth", true);
            prop.put("mail.smtp.starttls.enable", "true");
            prop.put("mail.smtp.host", host);
            prop.put("mail.smtp.port", port);
            prop.put("mail.smtp.ssl.trust", host);
    
            this.username = username;
            this.password = password;
        }
    
        public void sendMail(String from,String to,String subject, String msg) throws Exception {
    
            Session session = Session.getInstance(prop, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
    
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);
    
            MimeBodyPart mimeBodyPart = new MimeBodyPart();
            mimeBodyPart.setContent(msg, "text/html; charset=utf-8");
    
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(mimeBodyPart);
    
            message.setContent(multipart);
    
            Transport.send(message);
}
        }
Run Code Online (Sandbox Code Playgroud)

然后像这样调用该函数:

new EmailService("smtp.gmail.com", 587, "<emailID>", "<pass(not the actual gmail-account password if you're using gmail for this>")
                    .sendMail("<emailID>",
                            toemail,
                            "<title>",
                            "<body>);
Run Code Online (Sandbox Code Playgroud)

然而,这只是解决方案的一半。由于他们停止了Less Secure App AccessGmail 帐户的该功能,因此您现在应该通过不同的方式访问您的 Gmail 帐户。

App passwords您必须在该 Gmail 帐户上启用 2FA,并在您的 google 帐户下添加一个条目。之后,您在上述函数中提供的密码将是您从 gmail 帐户获得的“应用程序密码”(不是实际的 gmail 帐户密码,我相信这是自动生成的)。

在此输入图像描述

我不知道现在有任何其他电子邮件服务免费提供 smtp 电子邮件功能。他们都要求你以某种方式付款,除了gmail(如果我错了请纠正我)