环境: 引入javamail依赖
<dependency>
<groupId>javamail</groupId>
<artifactId>mail</artifactId>
<version>1.3.2</version>
</dependency>
2.JaveMail工具类
public class MailUtils4Prop {
private static String mail_host = null; // 设置发送邮件的服务器
private static String mail_send_user = null; // 发送人的帐号
private static String mail_send_pwd = null; // 发送人的密码
private static String mail_sender = null; // 设置发送者邮箱帐号
static {
try {
// 加载配置信息
Properties prop = new Properties(); prop.load(MailUtils4Prop.class.getClassLoader().getResourceAsStream("mail.properties"));
mail_host = prop.getProperty("mail.host");
mail_send_user = prop.getProperty("mail.send.user");
mail_send_pwd = prop.getProperty("mail.send.pwd");
mail_sender = prop.getProperty("mail.sender");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void sendMail(String email, String emailMsg) throws AddressException, MessagingException {
// 1.创建一个程序与邮件服务器会话对象 Session
Properties props = new Properties();
// 设置发送的协议
props.setProperty("mail.transport.protocol", "SMTP");
// 设置发送邮件的服务器
props.setProperty("mail.host", mail_host);
props.setProperty("mail.smtp.auth", "true");// 指定验证为true
// 创建验证器
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
// 设置发送人的帐号和密码
return new PasswordAuthentication(mail_send_user, mail_send_pwd);
}
};
Session session = Session.getInstance(props, auth);
// 2.创建一个Message,它相当于是邮件内容
Message message = new MimeMessage(session);
// 设置发送者
message.setFrom(new InternetAddress(mail_sender));
// 设置发送方式与接收者
message.setRecipient(RecipientType.TO, new InternetAddress(email));
// 设置邮件主题
message.setSubject("速运快递用户账号激活");
// message.setText("这是一封激活邮件,请<a href='#'>点击</a>");
// 设置邮件内容
message.setContent(emailMsg, "text/html;charset=utf-8");
// 3.创建 Transport用于将邮件发送
Transport.send(message);
}
public static void main(String[] args) throws Exception {
MailUtils4Prop.sendMail("abc@bos.com", "测试邮件");
}
}
配置文件
mail.host=127.0.0.1
mail.send.user=admin
mail.send.pwd=123456
mail.sender=admin@bos.com