javamail 实现邮件发送(基于qq邮箱)



qq邮箱提供smtp服务分两种,一种是企业邮箱(默认是开启的);另外一种是个人邮箱(需要自己开启,并且获得认证码)

如下代码实现,这个是默认是基于企业邮箱的实现:


package com.test;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import java.util.Date;
import java.util.Properties;

public class TestSendMail {

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

        String protocol = "smtp";
        String userName = "****@***.cn";//你的邮箱地址
        //qq 企业邮箱的链接方式
        String smtpServer ="smtp.exmail.qq.com";
        String password = "*****";

        //qq 个人邮箱链接方式
        //String password = "*********"; qq个人邮箱需要自己开启 smtp服务,需要发短信验证,开启完成会给你一个认证码
        //String smtpServer = "smtp.qq.com"; qq个人邮箱服务

        String from ="******@*****.cn";
        String to = "*******@***.com";

        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", protocol);
        props.setProperty("mail.host", smtpServer);
        props.setProperty("mail.smtp.auth", "true");
        props.put("mail.user", userName);
        props.put("mail.password", password);

        // 构建授权信息,用于进行SMTP进行身份验证
        Authenticator authenticator = new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };
        Session session = Session.getInstance(props, authenticator);
        session.setDebug(true);//可以看调适信息
        //创建代表邮件的MimeMessage对象
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSentDate(new Date());

        String subject = "测试邮件";
        String body = "authenticator 测试";
        // 使用指定的base64方式编码,并指定编码内容的字符集是gb2312
        message.setSubject(MimeUtility.encodeText(subject)); //B为base64方式

        message.setText(body); //B为base64方式
        //保存并且生成邮件对象
        message.saveChanges();

        //建立发送邮件的对象
        Transport.send(message);
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值