Java使用QQ邮箱发送邮件

本文介绍如何使用JavaMail API和JAF实现从Java应用程序中发送带HTML内容的电子邮件。包括下载必要的jar包、配置邮件服务器及发送邮件的具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.下载jar包

下载JavaMail下载JAF

2.将mail.jar 和 activation.jar两个jar包导入项目

3.发送邮件代码如下

public static boolean sendEmail(String to, String title, String content, String from, String key) {

        String host = "smtp.qq.com"; // QQ 邮件服务器

        Properties properties = System.getProperties();// 获取系统属性
        properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
        properties.put("mail.smtp.auth", "true");
        MailSSLSocketFactory sf;
        try {
            sf = new MailSSLSocketFactory();
        } catch (GeneralSecurityException e) {
            return false;
        }
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(from, key); // 发件人邮件用户名、密码
            }
        });
        try {
            MimeMessage message = new MimeMessage(session);// 创建默认的
                                                            // MimeMessage对象
            message.setFrom(new InternetAddress(from, "测试", "UTF-8"));// Set
            // From:头部头字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));// Set
                                                                                    // To:头部头字段
            message.setSubject(title, "UTF-8");// Set Subject:头部头字段
            message.setContent(content, "text/html;charset=UTF-8");// 设置消息体
            message.setSentDate(new Date());
            Transport.send(message);// 发送消息
        } catch (MessagingException | UnsupportedEncodingException mex) {
            return false;
        }
        return true;
    }

4.需要导入的包

import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
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.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.util.MailSSLSocketFactory;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值