使用javaMail发送邮件

import com.sun.mail.util.MailSSLSocketFactory;

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

/**
* 需要mail.jar
* 需要对发送邮箱开启POP3/SMTP服务,并保存授权密码
* Created by hgc on 2017/8/18.
*/
public class AutoboxingAndUnboxing{
public static void main(String[] args) throws Exception {
String to =”xxx@qq.com”;// 收件人电子邮箱
String from = “xxxx@qq.com”;// 发件人电子邮箱
String host = “smtp.qq.com”;//指定发送邮件的主机为 smtp.qq.com,该主机为QQ 邮件服务器
Properties properties = System.getProperties(); // 获取系统属性
properties.setProperty(“mail.smtp.host”,host);// 设置邮件服务器
/**
* 关于QQ邮箱,还要设置SSL加密,加上以下代码即可
*/
properties.put(“mail.smtp.auth”, “true”);
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put(“mail.smtp.ssl.enable”, “true”);
properties.put(“mail.smtp.ssl.socketFactory”, sf);

    Session session = Session.getDefaultInstance(properties,new Authenticator(){
        public PasswordAuthentication getPasswordAuthentication(){
            return new PasswordAuthentication("xxx@qq.com", "password"); //发件人邮件用户名、密码,使用的是授权密码
        }
    });

    MimeMessage message = new MimeMessage(session);// 创建默认的 MimeMessage 对象
    message.setFrom(new InternetAddress(from));// Set from: 头部头字段(正常邮箱发送中的发件人)
    message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));// Set To: 头部头字段(正常邮箱发送中的收件人)
    message.setSubject("This is the Subject Line!");// Set Subject: 头部头字段(正常邮箱发送的主题)
    message.setText("This is actual message"); // 设置消息体(正常邮箱发送的正文)
    Transport.send(message);// 发送消息
    System.out.println("Sent message successfully....");
}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值