JavaMail基本操作:
1. 创建properties对象
2. properties对象添加属性
l 添加发送邮件的邮件服务器属性
l 添加帐号密码校验属性
3. 用properties对象构建一个session
4. 用session构造消息对象
5. 设置消息内容
6. 消息对象设置发件人地址
7. 消息对象设置收件人地址
8. 连接服务器的邮箱
9. 发送邮件到目标地址
10. 关闭服务
简单示例:
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 TestJavaMail {
public static void main(String[] args) throws MessagingException {
Properties props = new Properties();
//设置发送邮件的邮件服务器属性
props.put("mail.smtp.host", "smtp");
//需要授权验证
props.put("mail.smtp.auth", "true");
//用properties构建一个session
Session session = Session.getInstance(props);
//定义消息对象
MimeMessage message = new MimeMessage(session);
//设置消息文本内容
message.setContent("Hello", "text/plain");
//地址
Address address = new InternetAddress("XXXX@163.com");
//发件人地址
message.setFrom(address);
//收件人地址
message.addRecipient(Message.RecipientType.TO, new InternetAddress(
"XXXX@qq.com"));
Transport transport = session.getTransport("smtp");
//连接服务器的邮箱
transport.connect("smtp.163.com", "XXXX", "*********");
//发送邮件到目标地址
transport.sendMessage(message, message.getAllRecipients());
//关闭服务
transport.close();
System.out.println("发送成功!");
}
}
***使用Multipart对象完成添加附件***