利用mail.jar发送邮件(简单版)

1 篇文章 0 订阅
  1. 下载mail.jar
  2. 打开邮箱的smtp服务(以QQ邮箱为例)

    点击设置,进入账户
    这里写图片描述
    开启SMTP服务这里写图片描述
    记住授权码,千万别泄露
    这里写图片描述
  3. 测试代码:
package test;

import java.io.UnsupportedEncodingException;
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;

public class Test {
    static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
    public static void main(String[] args) {
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.qq.com");//服务器名称
        //设置SSL,否则QQ邮箱不允许发送
        props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.port", "465");
        props.setProperty("mail.smtp.socketFactory.port", "465");

        props.put("mail.smtp.from", "2028953318@qq.com");//发送方邮箱地址
        props.put("mail.smtp.auth", "true");//需要验证,不验证会提示没有权限发送
        props.put("mail.smtp.user", "YuFeng");//发送方的发送名;
        props.put("mail.debug", "true");//输出相关信息(可以设置false不输出)
        Authenticator auth = new Authenticator() {//设置验证信息
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("2028953318@qq.com", "*******");//用户名+授权码
            }
        };
        Session session = Session.getInstance(props, auth);

        try {
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom();
            msg.setRecipients(Message.RecipientType.TO,
                              "*@163.com");//
            msg.setSubject("主题");
            msg.setSentDate(new Date());
            try {
                msg.setText(new String("正文\n".getBytes(),"UTF-8"));//设置编码格式
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Transport.send(msg);
        } catch (MessagingException mex) {
            System.out.println("send failed, exception: " + mex);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值