JavaMail 550 5.7.1 Unable to relay异常解决方法

问题描述:

在使用公司邮箱通过JavaMail发送外部邮件例如发送到OUTLOOK邮箱,163邮箱等时,程序会报异常

javax.mail.SendFailedException: Invalid Addresses;
  nested exception is:
    com.sun.mail.smtp.SMTPAddressFailedException: 550 5.7.1 Unable to relay

可尝试以下解决方法:

增加smtp属性认证,以及指定TLSv1.2协议

// 设置邮件服务器属性
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.auth", "true");
properties.put("mail.smtp.ssl.protocols", "TLSv1.2");

以下是完整测试代码,可参考:

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendMail {
     
        public static void main(String [] args)
        {
            // 收件人电子邮箱
            String to = "xxxxx@163.com";

            // 发件人电子邮箱
            String from = "xxxxx@xxxx.com.cn";

            // 指定发送邮件的主机
            String host = "xxx.x.x.x";

            // 获取系统属性
            Properties properties = System.getProperties();

            // 设置邮件服务器
            properties.setProperty("mail.smtp.host", host);
            properties.setProperty("mail.smtp.auth", "true");
            properties.put("mail.smtp.ssl.protocols", "TLSv1.2");

            // 发件人邮箱的用户名和密码
            String username = "your-email-userame";
            String password = "your-email-password"; // 替换为你的邮箱密码或应用密码

            // 创建一个 Authenticator 对象
            Authenticator auth = new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            };

            // 设置 Session 对象使用 Authenticator
            Session session = Session.getInstance(properties, auth);

            // 获取默认session对象
           // Session session = Session.getDefaultInstance(properties);
            try{
                // 创建默认的 MimeMessage 对象
                MimeMessage message = new MimeMessage(session);

                message.setFrom(new InternetAddress(from));

                message.addRecipient(Message.RecipientType.TO,
                        new InternetAddress(to));

                message.setSubject("This is the Subject Line!");

                // 设置消息体
                message.setText("This is actual message");

                // 发送消息
                Transport.send(message);
                System.out.println("Sent message successfully....");
            }catch (MessagingException mex) {
                mex.printStackTrace();
            }
        }
    }

参考文章:

线上发送邮件问题记录(Could not connect to SMTP host:smtp.exmail.qq.com,port:465)_javax.mail.messagingexception: could not connect t-优快云博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值