JAVA用email.jar发送邮件

1 jar包

 email.jar包,网上下载

2 源代码

复制代码
package zjr.amy.emil.test;

import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;

/**
 * 发邮件测试
 * @author zhujinrong
 *
 */
public class MailTest {
    
    static Authenticator auth = new Authenticator(){
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            // TODO Auto-generated method stub
            return new PasswordAuthentication("1251759009@qq.com", "密码");
        }
    };

    /**
     * 主函数
     * @param args
     */
    public static void main(String[] args) throws MessagingException {
        // TODO Auto-generated method stub
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.qq.com");
        props.put("mail.smtp.auth", "true");
        props.put("mail.from", "1251759009@qq.com");
        Session session = Session.getInstance(props, auth);
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom();
        msg.setRecipients(Message.RecipientType.TO, "2804163771@qq.com");
        msg.setSubject("JavaMail hello world example");
        msg.setSentDate(new Date());
        msg.setText("<html><body><span style='color:red;'>Hello world!</span></body></html>", "utf-8", "html");
        Transport.send(msg);
    }
}
复制代码

3 运行结果

4 遇到的错误

复制代码
Exception in thread "main" javax.mail.AuthenticationFailedException: 454 Authentication failed, please open smtp flag first!

    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:826)
    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:761)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:685)
    at javax.mail.Service.connect(Service.java:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at zjr.amy.emil.test.MailTest.main(MailTest.java:46)
复制代码

原因:没有qq邮箱没有开启smtp服务

解决方法:在QQ邮箱的设置里面,找到账户-》POP3/IMAP/SMTP选择开启POP3/SMTP服务

5 git地址

 git地址:https://github.com/HelloAmy/JavaStudy.git

posted on   BestNow  阅读(1202)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示