javamail QQ邮箱发送实例

来源:互联网 发布:sql语句修改字段名 编辑:程序博客网 时间:2024/05/05 15:28

开发环境 JDK1.7 javamail1.4.4

1.QQ邮箱发送邮件需要开启POP3/SMTP服务
实例图片

2.记住授权码
授权码

3.不说废话直接上代码
import java.io.UnsupportedEncodingException;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class TestSend {

public static void main(String[] args) throws MessagingException, UnsupportedEncodingException {     try {         Properties properties = new Properties();          properties.put("mail.transport.protocol", "smtp");// 连接协议                  properties.put("mail.smtp.host", "smtp.qq.com");// 主机名                  properties.setProperty("mail.transport.protocol", "smtp");//发送邮件协议名称          properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");          properties.put("mail.smtp.port", 465);// 端口号                  properties.put("mail.smtp.socketFactory.port", 465);          properties.put("mail.smtp.auth", "true");                  properties.put("mail.smtp.ssl.enable", "true");//设置是否使用ssl安全连接  ---一般都使用                  properties.put("mail.debug", "true");//设置是否显示debug信息  true 会在控制台显          //创建会话          Session session = Session.getInstance(properties);          //填写信封写信          Message msg = new MimeMessage(session);          msg.setSubject("激活邮箱!");          msg.setText("发送成功");          //邮件发送者          msg.setFrom(new InternetAddress("发送人QQ邮箱"));          //发送邮件          Transport transport = session.getTransport();          //连接自己的邮箱账户                  transport.connect("发送人QQ邮箱", "授权吗");//密码为刚才得到的授权码                  transport.sendMessage(msg, new Address[] { new InternetAddress("收件人QQ邮箱") });        } catch (Exception e) {            e.printStackTrace();        }}

}

注:1.4.1版本javamail可能会出现版本问题

0 0
原创粉丝点击