一:pom配置 jar包
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.5</version>
</dependency>
二:需要发送邮件的端口,服务,邮件及账户和秘密
配置在mail.properties
email.host=mailsss
email.port=25
email.template.path=\\cn\\sss\\ssss\\mail\\temp
email.from=发送的邮件账户
username=名字
password=秘密
三:操作类
public class EmailHelper {
private static final ResourceBundle bundle = ResourceBundle.getBundle("mail");
private static final String sendFrom = bundle.getString("email.from");
private static final String username = bundle.getString("username");
private static final String password = bundle.getString("password");
private static final String host = bundle.getString("email.host");
public static void sendEmail(String someone, String subject, String content){
Properties props = new Properties();
props.setProperty("mail.host", host);
props.setProperty("mail.smtp.auth", "true");
Authenticator authenticator = new Authenticator(){
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username,password);
}
};
Session session = Session.getDefaultInstance(props, authenticator);
session.setDebug(true);
Message message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(sendFrom));
message.setRecipients(RecipientType.TO,InternetAddress.parse(someone));
//message.setRecipients(RecipientType.TO,InternetAddress.parse("测试的接收的邮件多个以逗号隔开"));
try {
message.setSubject(subject);
message.setContent(content,"text/html;charset=UTF-8");
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
四:测试方法
@Test
public void tsetemail(){
String content ="哈喽你好!";
EmailHelper.sendEmail("[email protected]", "提示", content);
}