这是JavaMail的hello world级别程序
前期准备需要两步:
1:下载jar包:javax.mail.jar
https://github.com/javaee/javamail/releases
2:在 QQ 邮箱里的 设置->账户里开启 SMTP 服务
点击开启,发送邮件后,会得到一个验证码,代码中需要该验证码,以供验证,
SMTP(simple mail transfer protocol),
3:代码
package Mail;
import java.security.GeneralSecurityException;
import java.text.SimpleDateFormat;
import java.util.Date;
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;
import com.sun.mail.util.MailSSLSocketFactory;
public class SendEmail {
public static void main(String[] args) throws MessagingException, GeneralSecurityException {
Properties props = new Properties();
// 开启debug调试
props.setProperty("mail.debug", "true");
// 发送服务器需要身份验证
props.setProperty("mail.smtp.auth", "true");
// 设置邮件服务器主机名
props.setProperty("mail.host", "smtp.qq.com");
// 发送邮件协议名称
props.setProperty("mail.transport.protocol", "smtp");
// 开启SSL加密,否则会失败
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf);
// 创建session
Session session = Session.getInstance(props);
// 创建邮件
Message msg = new MimeMessage(session);
// 设置标题
msg.setSubject("测试邮件");
// 编辑内容
StringBuilder builder = new StringBuilder();
builder.append("这是一封java mail测试邮件\n");
builder.append("这是第二行");
builder.append("\n时间 " + getStringDate());
// 设置内容
msg.setText(builder.toString());
// 发送的邮箱地址
msg.setFrom(new InternetAddress("164691417@qq.com"));
// 通过session得到transport对象
Transport transport = session.getTransport();
// 连接邮件服务器:邮箱类型,帐号,授权码代替密码(更安全)
transport.connect("smtp.qq.com", "你的Qq号@qq.com", "第二步获取到的验证码");
// 发送邮件
transport.sendMessage(msg, new Address[] { new InternetAddress("收件箱@qq.com") });
transport.close();
}
/**
* 获取当前时间
* @return String
*/
public static String getStringDate() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = formatter.format(currentTime);
return dateString;
}
}
直接运行即可
=================================
有关Java Mail api中重要的几个类
Session 代表邮件会话,它从properties对象中获取信息,如代码中的SMTP服务器地址,协议,用户名密码等信息
Message 代表电子邮件:地址信息,邮件标题,邮件接收日期发送日期,正文和附件等
Address 邮件地址
Transport 负责发送邮件:send方法发邮件