1.本文提供一个java编写的发送邮件工具类。直接新建工具类,复制代码即可。
import java.security.GeneralSecurityException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.sun.mail.util.MailSSLSocketFactory;
public class SendMailUtil {
public static void sendMailUtil(ArrayList<String> to)
throws GeneralSecurityException, AddressException {
InternetAddress[] sendTo = new InternetAddress[to.size()];
for (int i = 0; i < to.size(); i++) {
sendTo[i] = new InternetAddress(to.get(i));
}
final String from = "xxx@sineva.com.cn";
String host = "pop.exmail.qq.com";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
properties.put("mail.smtp.auth", "true");
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
Session session = Session.getDefaultInstance(properties, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from, "发件人邮箱密钥");
}
});
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(MimeMessage.RecipientType.TO, sendTo);
message.setSubject("这个是邮件的主题");
message.setContent("这里边的内容是html代码",
"text/html;charset=gb2312");
Transport.send(message);
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
2.测试信息
@Test
public void name() throws AddressException, GeneralSecurityException {
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("xxx@qq.com");
arrayList.add("xxx@163.com");
SendMailUtil.sendMailUtil(arrayList)
}
3.所需jar包(maven)
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>