Java实现QQ邮件发送

QQ邮件发送

可以发送文本,图片,附件,同时可以将它们进行拼接发送。
功能代码被分成了4个方法,每个方法分别代表不同的发送方式,选择自己需要的方法即可。
**实现发送邮件之前,先准备好QQ授权码。**

一、获取授权码

  1. 打开QQ邮箱

  2. 点击设置
    在这里插入图片描述

  3. 点击账户

在这里插入图片描述

  1. 开启POP3/SMTP服务,我这里是开启的
    在这里插入图片描述

  2. 找到下方的温馨提醒,点击生成授权码
    在这里插入图片描述

  3. 验证密保,选择一种方式即可

在这里插入图片描述

  1. 授权码生成,复制保存一下,代码中需要

在这里插入图片描述

二、编写代码

1、pom.xml
<dependencies>
    <!--发送邮件-->
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4.7</version>
    </dependency>
    <dependency>
        <groupId>javax.activation</groupId>
        <artifactId>activation</artifactId>
        <version>1.1.1</version>
    </dependency>
</dependencies>
2、Java
/**
 * 作者:沈公子
 * 日期:2022/7/15 - 18:04
 * 作用:发送邮件
 * 需求:文本,图片,附件(文本,图片,视频,音乐)与拼接发送
 * setContent();    文本
 * setContentID();  图片
 * setFileName();   附件
 * 使用的路径是本项目的 resources 目录
 */
public class MailDemoSum {

    public static void main(String[] args) throws Exception {

        // 发送邮件(文本)
        //   testMail();
        
        // 发送邮件(图片)
        //   imageMail();
        
        // 发送邮件(附件:文本、图片、视频、音乐等)
        //  annexMail();

        // 发送邮件(文本,附件,图片,拼接)
        splitMail();
        
    }


    /**
     * 文本,附件,图片,拼接邮件
     */
    private static void splitMail() throws Exception {

        // 给用户发送邮件的邮箱
        final String from = "发件人QQ邮箱";
        // 邮箱的用户名
        final String username = "发件人QQ邮箱或邮箱用户名";
        // 邮箱授权码
        final String password = "授权码";
        // 发送邮件的服务器地址,QQ服务器
        final String host = "smtp.qq.com";
        // 接收人邮箱
        final String to = "收件人QQ邮箱";
        // 邮件主题
        final String title = "邮件主题";

        // 使用QQ邮箱时配置
        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");    // 设置QQ邮件服务器
        prop.setProperty("mail.transport.protocol", "smtp");      // 邮件发送协议
        prop.setProperty("mail.smtp.auth", "true");      // 需要验证用户名和密码

        // 关于QQ邮箱,还要设置SSL加密,其他邮箱不需要
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);

        // 创建定义整个邮件程序所需的环境信息的 Session 对象,QQ才有,其他邮箱就不用了
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 发件人邮箱用户名,授权码
                return new PasswordAuthentication(username, password);
            }
        });

        // 开启 Session 的 debug 模式,这样就可以查看程序发送 Email 的运行状态
        session.setDebug(true);

        // 通过 session 得到 transport 对象
        Transport ts = session.getTransport();

        // 使用邮箱的用户名和授权码连上邮箱服务器
        ts.connect(host, username, password);

        // 创建邮件,写邮件
        // 需要传递 session
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from)); // 指明邮件的发件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));   // 指明邮件的收件人
        message.setSubject(title);     // 邮件主题

        // 图片
        MimeBodyPart body1 = new MimeBodyPart();
        body1.setDataHandler(new DataHandler(new FileDataSource("D:\\Java\\JavaWeb\\daily_demo\\day40\\src\\main\\resources\\1.png")));
        body1.setContentID("1.png");

        // 文本
        MimeBodyPart body2 = new MimeBodyPart();
        body2.setContent("我不是广告,<img src='cid:1.png'>", "text/html;charset=utf-8");

        // 附件
        MimeBodyPart body3 = new MimeBodyPart();
        body3.setDataHandler(new DataHandler(new FileDataSource("D:\\Java\\JavaWeb\\daily_demo\\day40\\src\\main\\resources\\sp.mp4")));
        body3.setFileName("sp.mp4");

        // 附件
        MimeBodyPart body4 = new MimeBodyPart();
        body4.setDataHandler(new DataHandler(new FileDataSource("D:\\Java\\JavaWeb\\daily_demo\\day40\\src\\main\\resources\\a.txt")));
        body4.setFileName("2.png");

        // 拼接邮件正文内容
        MimeMultipart mimeMultipart1 = new MimeMultipart();
        mimeMultipart1.addBodyPart(body1);
        mimeMultipart1.addBodyPart(body2);
        mimeMultipart1.setSubType("related");   // 文本和图片内嵌成功

        // 将拼装好的正文内容设置为主体
        MimeBodyPart contentText = new MimeBodyPart();
        contentText.setContent(mimeMultipart1);

        // 拼接附件与正文内容
        MimeMultipart allFile = new MimeMultipart();
        allFile.addBodyPart(body3);
        allFile.addBodyPart(body4);
        allFile.addBodyPart(contentText);
        allFile.setSubType("mixed");    // 正文和附件都存在邮件中,所以类型设置为 mixed,三种方式,两个附件单词都可用:mixed(附件) > related(附件) > alternative(纯文本)

        // 设置到消息中,保存修改
        message.setContent(allFile);  // 把最后编辑好的邮件放到消息当中
        message.saveChanges();   // 保存修改

        // 发送邮件
        ts.sendMessage(message, message.getAllRecipients());

        // 释放资源
        ts.close();
    }

    /**
     * 附件邮件发送(附件:文本、图片、视频、音乐等)
     */
    private static void annexMail() throws Exception {
        
 		// 给用户发送邮件的邮箱
        final String from = "发件人QQ邮箱";
        // 邮箱的用户名
        final String username = "发件人QQ邮箱或邮箱用户名";
        // 邮箱授权码
        final String password = "授权码";
        // 发送邮件的服务器地址,QQ服务器
        final String host = "smtp.qq.com";
        // 接收人邮箱
        final String to = "收件人QQ邮箱";
        // 邮件主题
        final String title = "邮件主题";

        // 使用QQ邮箱时配置
        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");    // 设置QQ邮件服务器
        prop.setProperty("mail.transport.protocol", "smtp");      // 邮件发送协议
        prop.setProperty("mail.smtp.auth", "true");      // 需要验证用户名和密码

        // 关于QQ邮箱,还要设置SSL加密,其他邮箱不需要
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);

        // 创建定义整个邮件程序所需的环境信息的 Session 对象,QQ才有,其他邮箱就不用了
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 发件人邮箱用户名,授权码
                return new PasswordAuthentication(username, password);
            }
        });

        // 开启 Session 的 debug 模式,这样就可以查看程序发送 Email 的运行状态
        session.setDebug(true);

        // 通过 session 得到 transport 对象
        Transport ts = session.getTransport();

        // 使用邮箱的用户名和授权码连上邮箱服务器
        ts.connect(host, username, password);

        // 创建邮件,写邮件
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from)); // 指明邮件的发件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));   // 指明邮件的收件人
        message.setSubject(title);     // 邮件主题
        message.setDataHandler(new DataHandler(new FileDataSource("D:\\Java\\JavaWeb\\daily_demo\\day40\\src\\main\\resources\\aa.txt")));
        message.setFileName("sp.mp4");

        // 发送邮件
        ts.sendMessage(message, message.getAllRecipients());

        // 释放资源
        ts.close();
    }

    /**
     * 图片邮件发送
     */
    private static void imageMail() throws Exception {

      	// 给用户发送邮件的邮箱
        final String from = "发件人QQ邮箱";
        // 邮箱的用户名
        final String username = "发件人QQ邮箱或邮箱用户名";
        // 邮箱授权码
        final String password = "授权码";
        // 发送邮件的服务器地址,QQ服务器
        final String host = "smtp.qq.com";
        // 接收人邮箱
        final String to = "收件人QQ邮箱";
        // 邮件主题
        final String title = "邮件主题";

        // 使用QQ邮箱时配置
        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");    // 设置QQ邮件服务器
        prop.setProperty("mail.transport.protocol", "smtp");      // 邮件发送协议
        prop.setProperty("mail.smtp.auth", "true");      // 需要验证用户名和密码

        // 关于QQ邮箱,还要设置SSL加密,其他邮箱不需要
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);

        // 创建定义整个邮件程序所需的环境信息的 Session 对象,QQ才有,其他邮箱就不用了
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 发件人邮箱用户名,授权码
                return new PasswordAuthentication(username, password);
            }
        });

        // 开启 Session 的 debug 模式,这样就可以查看程序发送 Email 的运行状态
        session.setDebug(true);

        // 通过 session 得到 transport 对象
        Transport ts = session.getTransport();

        // 使用邮箱的用户名和授权码连上邮箱服务器
        ts.connect(host, username, password);

        // 创建邮件,写邮件
        // 需要传递 session
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from)); // 指明邮件的发件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));   // 指明邮件的收件人
        message.setSubject(title);     // 邮件主题

        // 准备图片数据
        MimeBodyPart image = new MimeBodyPart();
        // 图片需要经过数据处理,DataHandler:数据处理
        DataHandler dh = new DataHandler(new FileDataSource("D:\\Java\\JavaWeb\\daily_demo\\day40\\src\\main\\resources\\1.png"));
        image.setDataHandler(dh);   // 在我们的 Body 中放入这个处理的图片数据
        image.setContentID("imageID");    // 给图片设置一个ID,后面需要,设置 cid

        // 准备正文数据
        MimeBodyPart text = new MimeBodyPart();
        text.setContent("图片邮件<img src='cid:imageID'>", "text/html;charset=UTF-8"); // 邮件内容

        // 拼接文本与图片
        MimeMultipart mm = new MimeMultipart();
        mm.addBodyPart(text);
        mm.addBodyPart(image);
        mm.setSubType("related");    // 三种方式,两个附件单词都可用:mixed(附件) > related(附件) > alternative(纯文本)

        // 设置到消息中,保存修改
        message.setContent(mm);  // 把最后编辑好的邮件放到消息当中
        message.saveChanges();   // 保存修改

        // 发送邮件
        ts.sendMessage(message, message.getAllRecipients());

        // 释放资源
        ts.close();
    }

    /**
     * 文本邮件发送
     */
    private static void testMail() throws Exception {
      // 给用户发送邮件的邮箱
        final String from = "发件人QQ邮箱";
        // 邮箱的用户名
        final String username = "发件人QQ邮箱或邮箱用户名";
        // 邮箱授权码
        final String password = "授权码";
        // 发送邮件的服务器地址,QQ服务器
        final String host = "smtp.qq.com";
        // 接收人邮箱
        final String to = "收件人QQ邮箱";
        // 邮件主题
        final String title = "邮件主题";

        // 使用QQ邮箱时配置
        Properties prop = new Properties();
        prop.setProperty("mail.host", "smtp.qq.com");    // 设置QQ邮件服务器
        prop.setProperty("mail.transport.protocol", "smtp");      // 邮件发送协议
        prop.setProperty("mail.smtp.auth", "true");      // 需要验证用户名和密码

        // 关于QQ邮箱,还要设置SSL加密,其他邮箱不需要
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        prop.put("mail.smtp.ssl.enable", "true");
        prop.put("mail.smtp.ssl.socketFactory", sf);

        // 创建定义整个邮件程序所需的环境信息的 Session 对象,QQ才有,其他邮箱就不用了
        Session session = Session.getDefaultInstance(prop, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                // 发件人邮箱用户名,授权码
                return new PasswordAuthentication(username, password);
            }
        });

        // 开启 Session 的 debug 模式,这样就可以查看程序发送 Email 的运行状态
        session.setDebug(true);

        // 通过 session 得到 transport 对象
        Transport ts = session.getTransport();

        // 使用邮箱的用户名和授权码连上邮箱服务器
        ts.connect(host, username, password);

        // 创建邮件,写邮件
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from)); // 指明邮件的发件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));   // 指明邮件的收件人
        message.setSubject(title);     // 邮件主题
        message.setContent("邮件内容", "text/html;charset=utf-8");	// 邮件内容

        // 发送邮件
        ts.sendMessage(message, message.getAllRecipients());

        // 释放资源
        ts.close();

    }
}
  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现Java接收QQ邮件,您需要使用JavaMail API,它是一个用于发送和接收电子邮件Java API。以下是实现此功能的步骤: 1. 首先,您需要在QQ邮箱中启用SMTP和POP3协议。进入QQ邮箱设置 -> 账户 -> POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务,勾选“开启POP3/SMTP服务”。 2. 下载JavaMail API,并将其添加到您的Java项目中。JavaMail API是一个开源项目,可以在https://java.net/projects/javamail/downloads下载。 3. 编写Java代码以连接到QQ邮件服务器并接收电子邮件。以下是示例代码: ``` import java.util.Properties; import javax.mail.*; public class ReceiveEmail { public static void main(String[] args) { String host = "pop.qq.com"; String username = "your_qq_email_address"; String password = "your_qq_email_password"; Properties properties = new Properties(); properties.put("mail.pop3.host", host); properties.put("mail.pop3.port", "995"); properties.put("mail.pop3.starttls.enable", "true"); Session emailSession = Session.getDefaultInstance(properties); try { Store store = emailSession.getStore("pop3s"); store.connect(host, username, password); Folder emailFolder = store.getFolder("INBOX"); emailFolder.open(Folder.READ_ONLY); Message[] messages = emailFolder.getMessages(); for (int i = 0, n = messages.length; i < n; i++) { Message message = messages[i]; System.out.println("Subject: " + message.getSubject()); System.out.println("From: " + message.getFrom()[0]); System.out.println("Text: " + message.getContent().toString()); } emailFolder.close(false); store.close(); } catch (MessagingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } ``` 在上面的代码中,您需要将“your_qq_email_address”和“your_qq_email_password”替换为您的QQ邮箱地址和密码。此代码将连接到QQ邮件服务器,打印收件箱中的所有电子邮件的主题,发件人和正文。 希望这可以帮助您实现Java接收QQ邮件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值