您的位置:首页 > 编程语言 > Java开发

使用java发送邮件简单的例子

2017-01-10 18:17 525 查看
需要导入

 mail.jar
1.4.5

 activation.jar

package web;

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;

public class SendEmail
{
public static void main(String [] args)
{
// 收件人电子邮箱
String to = "xxx@163.com";

// 发件人电子邮箱
String from = "xxx@qq.com";

// 指定发送邮件的主机为 smtp.qq.com
String host = "smtp.qq.com"; //QQ 邮件服务器

// 获取系统属性
Properties properties = System.getProperties();

// 设置邮件服务器
properties.setProperty("mail.smtp.host", host);

properties.put("mail.smtp.auth", "true");
//QQ邮箱SSL需要加下面三句话
properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.smtp.port", "465");
properties.setProperty("mail.smtp.socketFactory.port", "465");
// 获取默认session对象
Session session = Session.getDefaultInstance(properties,new Authenticator(){
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("xxx@qq.com", "这里是在第三方客户端登录时需要的授权码,"); //发件人邮件用户名、授权码(替代密码功能)
}
});

try{
// 创建默认的 MimeMessage 对象
MimeMessage message = new MimeMessage(session);

// Set From: 头部头字段
message.setFrom(new InternetAddress(from));

// Set To: 头部头字段
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));

// Set Subject: 头部头字段
message.setSubject("This is the Subject Line!");

// 设置消息体
message.setText("This is actual message");

// 发送消息
Transport.send(message);
System.out.println("Sent message successfully....from w3cschool.cc");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: