亚洲国产日韩欧美在线a乱码,国产精品路线1路线2路线,亚洲视频一区,精品国产自,www狠狠,国产情侣激情在线视频免费看,亚洲成年网站在线观看

Spring如何實(shí)現(xiàn)郵件發(fā)送

時(shí)間:2024-07-26 14:02:53 SUN認(rèn)證 我要投稿
  • 相關(guān)推薦

Spring如何實(shí)現(xiàn)郵件發(fā)送

  Spring提供了一個發(fā)送郵件的抽象層,使發(fā)送郵件實(shí)現(xiàn)非常簡單。下面代碼需要mail.jar包,如果服務(wù)器需要認(rèn)證,必須加入如下加粗代碼:

Spring如何實(shí)現(xiàn)郵件發(fā)送

  源文件:SendMail.java:

  package mail;

  import org.springframework.mail.javamail.JavaMailSenderImpl;

  import org.springframework.mail.javamail.MimeMessageHelper;

  import javax.mail.internet.MimeMessage;

  import java.util.Properties;

  import java.util.Date;

  /**

  * @author chrischen

  */

  public class SendMail {

  //郵件發(fā)送器

  public static String Sender(String subject, String msg, String sendTo, String fromMail, String user, String pw, String fromName, String protocol, String host, String port){

  try{

  final String username = user;

  final String pass = pw;

  //需要認(rèn)證

  Properties props = new Properties();

  props.put(“mail.smtp.host”, host);

  props.put(“mail.smtp.auth”, “true”);

  props.put(“mail.transport.protocol”, protocol);

  props.put(“mail.from”, fromMail);

  //創(chuàng)建發(fā)送器

  JavaMailSenderImpl sender = new JavaMailSenderImpl();

  sender.setHost(host);

  sender.setUsername(username);

  sender.setPassword(pass);

  //創(chuàng)建消息

  MimeMessage message = sender.createMimeMessage();

  message.addHeader(“X-Mailer”, “Java Mailer”);

  MimeMessageHelper helper = new MimeMessageHelper(message);

  helper.setTo(sendTo);

  helper.setFrom(fromMail, fromName);

  helper.setSubject(subject);

  helper.setText(msg);

  helper.setSentDate(new Date());

  //開始發(fā)送

  sender.setJavaMailProperties(props);

  sender.send(message);

  }catch(Exception e){

  System.out.println(“Error:” + e);

  return “Failure”;

  }

  return “Success”;

  }

  //測試

  public static void main(String args[])throws Exception

  {

  String subject = “測試郵件”;//標(biāo)題

  String sendTo = “test@my.com”;//接收者郵件

  String fromMail = “send@my.com”;//發(fā)送者郵件

  String user = “send@my.com”;//發(fā)送者用戶

  String pw = “password”;//發(fā)送者郵件密碼

  String fromName = “Chen”;//發(fā)送者名字

  String protocol = “smtp”;//協(xié)議

  String host = “smtp.my.com”;//發(fā)送主機(jī)

  String port = “25”;//端口

  String msg = “簡單郵件發(fā)送。”;//發(fā)送內(nèi)容

  String ret = Sender(subject, msg, sendTo, fromMail, user, pw, fromName, protocol, host, port);

  System.out.println(“郵件發(fā)送結(jié)果:” + ret);

  }

  }

  使用MimeMessageHelper,可以實(shí)現(xiàn)Multipart email,方便添加附件和內(nèi)嵌資源等。

【Spring如何實(shí)現(xiàn)郵件發(fā)送】相關(guān)文章:

Linux認(rèn)證系統(tǒng)管理:linuxmail命令發(fā)送郵件失敗03-18

如何實(shí)現(xiàn)員工的有效激勵04-01

如何讓外商一定回復(fù)郵件03-21

Java byte[]轉(zhuǎn)int如何實(shí)現(xiàn)03-16

Java如何實(shí)現(xiàn)簡單的whois查詢03-16

如何實(shí)現(xiàn)對基層員工的有效激勵03-22

質(zhì)量管理創(chuàng)新如何實(shí)現(xiàn)03-26

如何更好地實(shí)現(xiàn)網(wǎng)站推廣03-29

旅游企業(yè)如何實(shí)現(xiàn)信息化02-28