java mail 发送邮件,并判断是否发送成功

来源:互联网 发布:python unicode 编辑:程序博客网 时间:2024/06/07 09:34

javamail 发邮件原理及步骤(仅是个人理解):

1.设置连接的服务器

2.验证账号密码是否正确,正确的话则获得权限

3.设置发送的内容

其实javamial只是给我们提供了链接到设置的某个邮箱的服务器上,具体的发邮件还是通过服务器发送的。下面是代码()

1.sendEmailUtil(连接邮箱服务器,验证权限,填充发送内容,我用的是163邮箱smtp协议,也可以使用其他的)

public class EmailUtil {//管理员向企业手动发发邮件public boolean sentEmail(String to,String title,String content){String from ="发件人邮箱";String password="客户端授权码";boolean falg =false;               Properties properties =new Properties();properties.put("mail.smtp.host", "smtp.163.com");                properties.put("mail.smtp.port", "25");                properties.put("mail.smtp.auth", "true");        try {         Authenticator authenticator = new Email_Authenticator(from, password);             javax.mail.Session sendMailSession = javax.mail.Session.getDefaultInstance(properties, authenticator);             MimeMessage mailMessage = new MimeMessage(sendMailSession);mailMessage.setFrom(new InternetAddress(from)); mailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(to));        mailMessage.setSubject(title, "UTF-8");        mailMessage.setSentDate(new Date());        //邮件内容        Multipart mainPart = new MimeMultipart();        BodyPart html = new MimeBodyPart();        html.setContent(content, "text/html; charset=utf-8");        mainPart.addBodyPart(html);        mailMessage.setContent(mainPart);        Transport.send(mailMessage);        falg=true;} catch (AddressException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (MessagingException e) {// TODO Auto-generated catch blocke.printStackTrace();}                       return falg;}
2.后台调用

//管理员向用户发邮件(我是在ssh框架下写的)public String sendEmail() throws AddressException, MessagingException{//Email email =emailService.sendEmail(t_from);e_msg="false";EmailUtil emailUtil =new EmailUtil();if(emailUtil.sentEmail(to, title, content)){e_msg="true";}return "success";}
3.jsp页面

   //发邮件      function sendEmail(){      alert("发邮件");      var to =$("#to").val();      var title=$("#title").val();      var content=$("textarea").val();      $.post("data/sendEmail",      {      "to":to,      "title":title,      "content":content      },function(json){      if(json.e_msg =="true"){      layer.msg('发送成功', {icon: 1});      <!--再次在发一次post,将发送的邮件的信息保存在数据库,并将是否发送成功字段设为Y -->      }else{      layer.msg('发送失败', {icon: 2});      <!--再次在发一次post,将发送的邮件的信息保存在数据库,并将是否发送成功字段设为N-->      }      },"json");      
4.效果展示

5.我这这个发送成功失败是在有网路和没网络的情况下产生的,所以我需要获得发送失败的提醒方便我再将数据进行保存,如果发送失败直接将此条邮件设在草稿箱或发送失败中,至于邮箱格式等发在前段判断,提交到后台在判断一下,不用再util中判断。

2 1
原创粉丝点击