Enviar e-mail a lograr con Java

Enviar por correo electrónico (mensajes de texto sencillo)

El primer paso, dependencia de las importaciones

Enviar correo electrónico tiene las dependencias necesarias

< Dependencia > 
 < groupId > javax.mail </ groupId >
 < artifactId > correo electrónico </ artifactId >
 < versión > 1.4.7 </ version >
</ dependencia > < dependencia > < groupId > javax.activation </ groupId > < artifactId > activación </ artifactId > < versión > 1.1.1 </ versión > </ dependencia


 
 
 
>

A continuación, crear una página estática

Página incluye el código de verificación de contenido electrónico enviado por el buzón del destinatario botón de envío

< Forma action = "$ {} pageContext.request.contextPath / test" method = "post" > 
  < p >自己的邮箱:       < input type = "email" name = "nombre de usuario" value = "[email protected]" > </ p >
  < p >验证码:         < entrada type = "contraseña" name = "PSW" value = "emzspejrljnvbfad" > </ p >
   < p >发给谁:         <de entrada type = "email" name = "touser"/> </ P >
   < p style = "color: red" >发送内容: </ p >
   < textarea name = "de área de texto" filas = "20" cols = "100" style = "font-size: 30px" > </ textarea >
   < p > < entrada type = "submit" value = "确定" > </ p > </ forma >

Información El tercer paso es recibir páginas enviadas desde

Al recibir el req servlet

String uesrname = req.getParameter("username");
String psw = req.getParameter("psw");
String touser = req.getParameter("touser");
String textarea = req.getParameter("textarea");

第四步,创建一个发邮件的方法

public static void t1(String username,String passwprd,String touser,String textarea) throws Exception{
   Properties properties = new Properties();
   properties.setProperty("mail.host","smtp.qq.com");//设置qq邮件服务器
   properties.setProperty("mail.transport.protocol","smtp");//邮件发送协议
   properties.setProperty("mail.smtp.auth","true");//需要验证用户名密码
   //qq邮箱还要ssl加密
   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() {
       @Override
       public PasswordAuthentication getPasswordAuthentication() {
           //发件人用户名授权码
           return new PasswordAuthentication("username","passwprd");
      }
  });

   session.setDebug(true);
   Transport transport = session.getTransport();
   transport.connect("smtp.qq.com","username","emzspejrljnvbfad");
   MimeMessage message = new MimeMessage(session);
   message.setFrom(new InternetAddress("username"));
   message.setRecipient(Message.RecipientType.TO,new InternetAddress("touser"));
   message.setSubject("****");
   message.setContent("textarea","text/html;charset=UTF-8");
   transport.sendMessage(message,message.getAllRecipients());
   transport.close();
}

第五步,调用方法并转发页面

try {
   test01.t1(uesrname,psw,touser,textarea);
} catch (Exception e) {
   e.printStackTrace();
}
resp.sendRedirect("/test_war/success.jsp");

自动发送邮件(线程)

常用在注册后发送短信

第一步,写一个简单的写邮箱的text框

<form action="${pageContext.request.contextPath}/test02" method="get">
   <input type="text" name="mailPath">
   <input type="submit">

第二步,获取框里的信息

String mailpath = req.getParameter("mailPath");

第三步,序列化信息

public class User {
   private String mailPath;

   @Override
   public String toString() {
       return "User{" +
               "mailPath='" + mailPath + '\'' +
               '}';
  }

   public String getMailPath() {
       return mailPath;
  }

   public void setMailPath(String mailPath) {
       this.mailPath = mailPath;
  }

   public User(String mailPath) {
       this.mailPath = mailPath;
  }
}

第四步,创线程,获取发送邮件路径

public class sendmail extends Thread {
   private User user;
   public sendmail(User user){
       this.user=user;
  }
   @Override
   public void run() {

       try {

           Properties properties = new Properties();
       properties.setProperty("mail.host","smtp.qq.com");//设置qq邮件服务器
       properties.setProperty("mail.transport.protocol","smtp");//邮件发送协议
       properties.setProperty("mail.smtp.auth","true");//需要验证用户名密码
       //qq邮箱还要ssl加密
       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() {
           @Override
           public PasswordAuthentication getPasswordAuthentication() {
               //发件人用户名授权码
               return new PasswordAuthentication("******@qq.com","*****");
          }
      });

      session.setDebug(true);
       Transport transport = session.getTransport();
       transport.connect("smtp.qq.com","******@qq.com","*****");
       MimeMessage message = new MimeMessage(session);
       message.setFrom(new InternetAddress("******@qq.com"));
       message.setRecipient(Message.RecipientType.TO,new InternetAddress(user.getMailPath()));
       message.setSubject("我是***");
       message.setContent("你好~","text/html;charset=UTF-8");
       transport.sendMessage(message,message.getAllRecipients());
       transport.close();
      } catch (GeneralSecurityException e) {
           e.printStackTrace();
      } catch (NoSuchProviderException e) {
           e.printStackTrace();
      } catch (MessagingException e) {
           e.printStackTrace();
      }
  }
}

第五步,执行线程,定向页面

User user = new User(mailpath);
sendmail sendmail = new sendmail(user);
sendmail.start();
resp.sendRedirect("/test_war/success.jsp");

带有附件/图片的邮件

把 message.setContent("你好~","text/html;charset=UTF-8");

变为

//图片
   MimeBodyPart body1 = new MimeBodyPart();
   body1.setDataHandler(new DataHandler(new FileDataSource(" ")));
   body1.setContentID("lt.png");
//文本
   MimeBodyPart body2 = new MimeBodyPart();
   body2.setContent("*************<img src='cid:lt.png' ","text/html;charset=utf-8");
//附件
   MimeBodyPart body3 = new MimeBodyPart();
   body3.setDataHandler(new DataHandler(new FileDataSource(" ")));
   body3.setFileName("lt1.properties");
//拼装
   MimeMultipart mimeMultipart =new MimeMultipart();
   mimeMultipart.addBodyPart(body1);
   mimeMultipart.addBodyPart(body2);
   mimeMultipart.setSubType("related");//文本和图片内嵌成功
//将拼装好的正文设置为主体
   MimeBodyPart contentText = new MimeBodyPart();

   contentText.setContent(mimeMultipart);
//拼接附件
   MimeMultipart allFile = new MimeMultipart();
   allFile.addBodyPart(body3);
   allFile.addBodyPart(contentText);
   allFile.setSubType("mixed");
message.setContent(allFile);
message.saveChanges();

Supongo que te gusta

Origin www.cnblogs.com/ltdh/p/12482201.html
Recomendado
Clasificación