利用Java实现QQ邮箱邮件发送

本文介绍了如何使用Java的Maven项目通过javax.mail库实现从QQ邮箱向指定邮箱发送带有HTML内容的邮件,涉及依赖导入、配置SMTP和SSL,以及获取并使用校验码进行身份验证。

一、新建一个Maven空项目,并导包

共需要两个jar

 <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.7</version>
    </dependency>

二、去QQ邮箱取得校验码

在这里插入图片描述
验证之后方可获取校验码,并牢记

3、创建类

11111111@qq.com邮箱,向22222222@qq.com发送邮件

import com.sun.mail.util.MailSSLSocketFactory;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class Main {
    public static void main(String[] args) throws Exception {
    	String 校验码="你的校验码";//将你的校验码放进去
        Properties properties = new Properties();
        properties.setProperty("mail.host","smtp.qq.com");
        properties.setProperty("mail.transport.protocol","smtp");
        properties.setProperty("mail.smtp.auth","true");
        //关于QQ邮箱,还需要设置SSL加密
        MailSSLSocketFactory mailSSLSocketFactory = new MailSSLSocketFactory();
        mailSSLSocketFactory.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable","true");
        properties.put("mail.smtp.ssl.socketFactory",mailSSLSocketFactory);

        //使用Java发送邮件的5步骤
//        1、定义整个应用程序所需的环境信息的Session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("11111111@qq.com", 校验码);
            }
        });
//        开启Session的deBug模式,查看运行状态
        session.setDebug(true);
//        2、通过Session得到transport对象
        Transport transport = session.getTransport();
//        3、使用邮箱的用户名和授权码连接服务器
        transport.connect("smtp.qq.com","11111111@qq.com",校验码);
//        4、创建邮件
        MimeMessage mimeMessage = new MimeMessage(session);

//        发件人
        mimeMessage.setFrom(new InternetAddress("11111111@qq.com"));
//        收件人
        mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress("22222222@qq.com"));

//        邮件的标题
          mimeMessage.setSubject("只包含文本的简单邮件");
//        文本内容,实际上是Html文件

        mimeMessage.setContent("<h1 style=\"color:red;\">你好啊!</h1>", "text/html;charset=UTF-8");
        //   5、发送邮件
        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
//        6、关闭
		transport.close();

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

科妙知行

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值