SMTP协议(发送邮件)
SMTP(Simple Mail Transfer Protocol)即简单邮件传输协议,是一组用于由源地址到目的地址传送邮件的规则,由它来控制信件的中转方式。
SMTP协议属于TCP/IP协议簇,它帮助每台计算机在发送或中转信件时找到下一个目的地。
SMTP服务器默认端口25
POP3协议
POP3(Post Office Protocol-Version 3)即邮局协议版本3
本协议主要用于支持使用客户端远程管理在服务器上的电子邮件
POP3服务器默认端口110
以QQ邮箱为例发送邮件
1.开启服务并获取授权码
2.编写Java代码
public class SendEmail {
public static void main(String [] args)
{
// 收件人电子邮箱
String to = "xiaowang@gmail.com";
// 发件人电子邮箱
String from = "123456789@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");
//配置SSL加密方式
properties.put("mail.smtp.port", "587");
//调试模式
//properties.put("mail.debug", "true");
// 获取默认session对象
Session session = Session.getDefaultInstance(properties,new Authenticator(){
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("123456789@qq.com", "lkpujjmztzaced"); //发件人邮件用户名、授权码
}
});
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("邮件消息标题");
// 设置消息体
message.setText("邮件消息具体内容");
// 发送消息
Transport.send(message);
System.out.println("邮件发送成功");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}