import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.zmt.mail.utils.DefaultMessage;
/**
* 作者: 薛俊鹏
* 时间: 2018年9月30日下午4:23:49
* 内容: 谷歌邮件发送
* 注:网络需要翻墙
* 状态: 编写
*/
public class GoogleMail {
/*
* gmail邮箱SSL方式
*/
private static void gmailssl(Properties props) {
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
props.put("mail.debug", "false");
props.put("mail.smtp.host", DefaultMessage.gmailServer);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
props.put("mail.smtp.port", DefaultMessage.gmailSerPort);
props.put("mail.smtp.socketFactory.port", DefaultMessage.gmailFacPort);
props.put("mail.smtp.auth", "true");
}
/*list_to:收件人、 list_cc:抄送人 */
public static boolean GmailSender(List<String> list_to,List<String> list_cc,String Context,String subject) {
// Get a Properties object
Properties props = new Properties();
boolean IsSend = true;
//选择ssl方式
gmailssl(props);
Session session = Session.getDefaultInstance(props,new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(DefaultMessage.gmailAccount, DefaultMessage.gmailPassword);
}
});
// -- Create a new message --
Message msg = new MimeMessage(session);
// -- Set the FROM and TO fields --
try {
msg.setFrom(new InternetAddress(DefaultMessage.gmailAccount));
/*邮件发送*/
for(Object receiveMail:list_to){
msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(receiveMail.toString()));
msg.setSubject(subject);
msg.setText(Context);
msg.setSentDate(new Date());
Transport.send(msg);
}
/*邮件抄送*/
for(Object copyMail:list_cc){
msg.setRecipients(Message.RecipientType.CC,InternetAddress.parse(copyMail.toString()));
msg.setSubject(subject);
msg.setText(Context);
msg.setSentDate(new Date());
Transport.send(msg);
}
} catch (Exception e) {
IsSend = false;
System.out.println("邮件发送请求超时,请查看谷歌邮箱相关协议规范【 Send by Service.】");
}
return IsSend;
}
}