java发送邮件(解决不被被当成垃圾邮件)

时间:2025-03-22 10:41:58

//登录验证

static class SmtpAuth extends {  

     private String user , password ;  
 
     public void getuserinfo(String getuser, String getpassword) {  
         user = getuser;  
         password = getpassword;  
     }  
 
     protected getPasswordAuthentication() {  
         return new ( user , password );  
     }  

  } 

//群发邮件

 public void sendMessage() throws MessagingException, IOException {

        String smtpHost = "smtp.";
        String from = userAccount;//传过来的账号
        String subject = "这是一份调查问卷";
        StringBuffer messageText=new StringBuffer();//内容以html格式发送,防止被当成垃圾邮件
        ("<h2>Hi,你好,这是一份充满诚意的调查问卷,如果有空的话请协助我们完成调查</h2></br>");
        ("<a href="+wenjuanUrl+">点我前往答题</a>");
        
        SmtpAuth sa = new SmtpAuth();
        (userAccount, userPassword);//传过来的账号和密码
         props = new ();
        ("", "true");
        ("", smtpHost);

        InternetAddress fromAddress = new InternetAddress(from,"苏州教育质量监测中心");//设置发送人别称

        int i = 0;
        int sucs=0;
        int fal=0;
        String result="";
        while (i < ()) {//email是存放收件人邮箱地址的集合
            try {
                InternetAddress toAddresss = new InternetAddress((i));
                Session mailSession = (props, sa);
                MimeMessage testMessage = new MimeMessage(mailSession);
                try {
                    (fromAddress);
                } catch (AddressException  e) {
                    result="false";
                    ().write(result);
                }
                (, toAddresss);
                (new ());
                (subject);
                //(messageText);
                ((), "text/html;charset=gb2312");
                (testMessage);
                i++;
                sucs++;
            } catch (MessagingException e) {
                ("发送给"+(i)+"发送失败");
                i++;
                fal++;
            }
        }
        result=sucs+"|"+fal;
        ().write(result);

}