【问题标题】:Java Mail Api send email failedJava Mail Api 发送电子邮件失败
【发布时间】:2020-04-19 21:31:02
【问题描述】:

javax.mail.MessagingException:无法连接到 SMTP 主机:smtp.gmail.com,端口:465; 嵌套异常是: java.net.ConnectException:无法从 /::(端口 58929)连接到 smtp.gmail.com/108.177.125.108(端口 465):连接失败:ECONNREFUSED(连接被拒绝)

代码sn-p

public GMailSender(String user, String password) {
   this.user = user;
   this.password = password;

   Properties props = new Properties();
   props.setProperty("mail.transport.protocol", "smtp");
   props.setProperty("mail.host", mailhost);
   props.put("mail.smtp.auth", "true");
   props.put("mail.smtp.port", "465");
   props.put("mail.smtp.socketFactory.port", "465");
   props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
   props.put("mail.smtp.socketFactory.fallback", "false");
   props.setProperty("mail.smtp.quitwait", "false");
   session = Session.getDefaultInstance(props, this);
}

【问题讨论】:

  • 你能出示你的代码吗
  • 为防止未经授权访问您的电子邮件,您需要在 Gmail.com 上登录您的帐户,然后打开另一个选项卡并转到不太安全的应用程序设置,然后选择“打开”。
  • 已经这样做了,但不工作
  • 确保您在发送电子邮件时已连接到互联网
  • 网络正常

标签: java smtp gmail jakarta-mail


【解决方案1】:

这对我有用:

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class Email {
    public static void main(String args[]) {
        final String username = "sender email address";
        final String password = "sender email password";

        Properties props  = new Properties();
        props.put("mail.smtp.auth","true");
        props.put("mail.smtp.starttls.enable","true");
        props.put("mail.smtp.host","smtp.gmail.com");
        props.put("mail.smtp.port","587");

        Session session = Session.getInstance(props, 
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(username, password);
                    }
        });           

        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("sender email address"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("receiver email address"));
            message.setSubject("First");
            message.setContent("<h1>hello</h1>","text/html");
            Transport.send(message);

            System.out.println("Email has been sent succesfully...");   
        }
        catch(MessagingException e) {
            throw new RuntimeException(e);
        }


    }
}

用正确的替换发件人/收件人电子邮件地址/密码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    • 2011-11-09
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多