java傳送郵件(解決不被被當成垃圾郵件)
//登入驗證
static class SmtpAuth extends javax.mail.Authenticator {
private String user , password ;public void getuserinfo(String getuser, String getpassword) {
user = getuser;
password = getpassword;
}
protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
return new javax.mail.PasswordAuthentication( user , password );
}
}
//群發郵件
public void sendMessage() throws MessagingException, IOException {
String smtpHost = "smtp.163.com";
String from = userAccount;//傳過來的賬號
String subject = "這是一份調查問卷";
StringBuffer messageText=new StringBuffer();//內容以html格式傳送,防止被當成垃圾郵件
messageText.append("<h2>Hi,你好,這是一份充滿誠意的調查問卷,如果有空的話請協助我們完成調查</h2></br>");
messageText.append("<a href="+wenjuanUrl+">點我前往答題</a>");
SmtpAuth sa = new SmtpAuth();
sa.getuserinfo(userAccount, userPassword);//傳過來的賬號和密碼
java.util.Properties props = new java.util.Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", smtpHost);
InternetAddress fromAddress = new InternetAddress(from,"蘇州教育質量監測中心");//設定傳送人別稱
int i = 0;
int sucs=0;
int fal=0;
String result="";
while (i < email.size()) {//email是存放收件人郵箱地址的集合
try {
InternetAddress toAddresss = new InternetAddress(email.get(i));
Session mailSession = Session.getDefaultInstance(props, sa);
MimeMessage testMessage = new MimeMessage(mailSession);
try {
testMessage.setFrom(fromAddress);
} catch (AddressException e) {
result="false";
response.getWriter().write(result);
}
testMessage.addRecipient(javax.mail.Message.RecipientType.TO, toAddresss);
testMessage.setSentDate(new java.util.Date());
testMessage.setSubject(subject);
//testMessage.setText(messageText);
testMessage.setContent(messageText.toString(), "text/html;charset=gb2312");
Transport.send(testMessage);
i++;
sucs++;
} catch (MessagingException e) {
System.out.println("傳送給"+email.get(i)+"傳送失敗");
i++;
fal++;
}
}
result=sucs+"|"+fal;
response.getWriter().write(result);
}