Java实现邮件发送,需要指定邮件服务器,和自己的邮箱账号和密码,谨记 自己的邮箱必须得到到客户端授权码,尤其是新开的邮箱,具体看代码,包括附件发送
public class EmailUtils {
private static String from = ""; //邮箱账号
private static String password = ""; //邮箱密码或者授权码
private static String host = ""; //邮箱服务器
public static boolean sendMail(String receiver[],String subject,String msg,String filePath) {
try {
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host); //设置邮箱服务器
properties.put("mail.smtp.auth", "true"); //设置验证
properties.put("mail.smtp.ssl.enable", "true");
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getInstance(properties, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() { // 邮箱服务器账户、第三方登录授权码
return new PasswordAuthentication(from, password); // 发件人邮件用户名、密码
}
});
MimeMessage message = new MimeMessage(session); //创建邮件内容
message.setFrom(new InternetAddress(from));
if(receiver == null || receiver.length == 0) {
return false;
}
InternetAddress ia[] = new InternetAddress[receiver.length];
for(int i=0;i<receiver.length;i++) {
ia[i] = new InternetAddress(receiver[i]);
}
message.addRecipients(Message.RecipientType.TO, ia); //设置接受者 类型为发送,也可改变类型为抄送 Message.RecipientType.CC
message.setSubject(subject);
// 创建消息部分
BodyPart messageBodyPart = new MimeBodyPart();
// 消息
messageBodyPart.setText(msg);
// 创建多重消息
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// 附件部分
if(StringUtils.isNotBlank(filePath)) {
File file = new File(filePath);
if(!file.exists()) {
return false;
}
String[] split = filePath.split("[/]");
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filePath);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(MimeUtility.encodeText(split[split.length-1],"utf-8","B")); //设置附件名 防止中文乱码
multipart.addBodyPart(messageBodyPart);
}
message.setContent(multipart);
Transport.send(message);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}