栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

使用spring框架中的组件发送邮件功能说明

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用spring框架中的组件发送邮件功能说明

Spring框架是由于软件开发的复杂性而创建的。Spring使用的是基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅仅限于服务器端的开发。从简单性、可测试性和松耦合性角度而言,绝大部分Java应用都可以从Spring中受益。

首先进入自己的QQ邮箱,在设置中修改账户信息

然后来至底部

点击开启,再用手机发送对应信息到指定号码,然后点击我已发送

获取授权码

注意提示:

到这里,相信你已经开通了SMTP服务,这样就可以在java code发送邮件了

接下来的是Spring 中使用邮件服务

首先是配置信息使用的是587端口,刚开始用465端口我纠结了好久(使用465端口的错误详情),用不了,你可以尝试,默认的25端口应该也是不适合的


  
    
    //或许你可以用465端口,默认的25不适合
    
    
    //这里的是你通过短信后,获取的授权码
    
     
       
 true 
 25000 
       
     
  
  
  
    
    
  
  
    
    
  

用maven引入的jar包

 
  
    org.springframework
    spring-context-support
    ${spring.version}
  
  
    javax.mail
    mail
    1.4.7
  

下面只是一个工具类作简单例子,请勿见怪

package cn.cherish.common;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

public class MailUtil {
  private static final String HOST = "smtp.qq.com";
  private static final String SMTP = "smtp";
  private static final String USERNAME = "785427346@qq.com";
  private static final String PASSWORD = "xxxxxxxxxx";
  private static final int PORT = 587;//587/465
  private static final String DEFAULTENCODING = "UTF-8";
  private static JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
  private static Properties prop = new Properties();
  static{
    // 设定mail server
    senderImpl.setHost(HOST);
    senderImpl.setProtocol(SMTP);
    senderImpl.setUsername(USERNAME);
    senderImpl.setPassword(PASSWORD);
    senderImpl.setPort(PORT);
    senderImpl.setDefaultEncoding(DEFAULTENCODING);
    // 设定properties
    prop.put("mail.smtp.auth", "true");
    prop.put("mail.smtp.timeout", "25000");
    //设置调试模式可以在控制台查看发送过程
    prop.put("mail.debug", "true");
    senderImpl.setJavaMailProperties(prop);
  }
  public static void main(String args[]) {
    // 设置收件人,寄件人 用数组发送多个邮件
//   String[] array = new String[] {"88888@qq.com","666666@qq.com","999999999@qq.com",USERNAME};
    String[] array = new String[] {USERNAME};
    String subject = "Cherish内嵌图片、音乐的邮件";
//   StringBuffer sb = new StringBuffer();
//   try {
//     URL url = new URL("http://www.imooc.com/");//http://android-studio.org/
//     
//     URLConnection conn = url.openConnection();
//     InputStream is = conn.getInputStream();
//     
//     BufferedReader reader = new BufferedReader(new InputStreamReader(is));
//     
//     String string = null;
//     while ((string = reader.readLine()) != null) {
//sb.append(string);
//     }
//     
//     //System.out.println(sb.toString());
//     
//   } catch (Exception e) {
//     e.printStackTrace();
//   }
//   
//   boolean result = htmlMail(array, subject, sb.toString());
    String filePath = "E:/javaxmail.png";
    String html = ""+
   ""+
   "爱你"+
   "Hello,Nice to meet you!"+
   "并摸了一把你的小奶"+
   ""+
   "";
    boolean result = inlineFileMail(array, subject, html, filePath);
    if (result) {
      System.out.println("发送邮件成功。。。。");
    }
  }
  
  public static boolean singleMail(String to, String subject, String content){
    String[] array = new String[] {to};
    return singleMail(array, subject, content);
  }
  
  public static boolean singleMail(String[] to, String subject, String content){
    boolean result = true;
    SimpleMailMessage mailMessage = new SimpleMailMessage();
    // 设置收件人,寄件人 用数组发送多个邮件
    mailMessage.setTo(to);
    mailMessage.setFrom(USERNAME);
    mailMessage.setSubject(subject);
    mailMessage.setText(content);
    // 发送邮件
    try {
      senderImpl.send(mailMessage);
    } catch (MailException e) {
      e.printStackTrace();
      result = false;
    }
    return result;
  }
  
  public static boolean htmlMail(String[] to, String subject, String html){
    boolean result = true;
    MimeMessage mailMessage = senderImpl.createMimeMessage(); 
    MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage); 
    try {
      // 设置收件人,寄件人 用数组发送多个邮件
      messageHelper.setTo(to);
      messageHelper.setFrom(USERNAME);
      messageHelper.setSubject(subject);
      // true 表示启动HTML格式的邮件 
      messageHelper.setText(html, true); 
      // 发送邮件
      senderImpl.send(mailMessage);
    } catch (MessagingException e) {
      result = false;
      e.printStackTrace();
    }
    return result;
  }
  
  public static boolean inlineFileMail(String[] to, String subject, String html, String filePath){
    boolean result = true;
    MimeMessage mailMessage = senderImpl.createMimeMessage(); 
    try {
      //设置true开启嵌入图片的功能
      MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true); 
      // 设置收件人,寄件人 用数组发送多个邮件
      messageHelper.setTo(to);
      messageHelper.setFrom(USERNAME);
      messageHelper.setSubject(subject);
      // true 表示启动HTML格式的邮件 
      messageHelper.setText(html, true); 
      FileSystemResource file = new FileSystemResource(new File(filePath)); 
      messageHelper.addInline(file.getFilename(), file); 
      // 发送邮件
      senderImpl.send(mailMessage);
    } catch (MessagingException e) {
      result = false;
      e.printStackTrace();
    }
    return result;
  }
  
  public static boolean attachedFileMail(String[] to, String subject, String html, String filePath){
    boolean result = true;
    MimeMessage mailMessage = senderImpl.createMimeMessage(); 
    try {
      // multipart模式 为true时发送附件 可以设置html格式
      MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true,"utf-8"); 
      // 设置收件人,寄件人 用数组发送多个邮件
      messageHelper.setTo(to);
      messageHelper.setFrom(USERNAME);
      messageHelper.setSubject(subject);
      // true 表示启动HTML格式的邮件 
      messageHelper.setText(html, true); 
      FileSystemResource file = new FileSystemResource(new File(filePath)); 
      // 这里的方法调用和插入图片是不同的。 
      messageHelper.addAttachment(file.getFilename(), file);
      // 发送邮件
      senderImpl.send(mailMessage);
    } catch (MessagingException e) {
      result = false;
      e.printStackTrace();
    }
    return result;
  }

温馨提示:

这是内嵌图片的方式 javaxmail.png 要和 messageHelper.addInline(file.getFilename(), file); 这里的 file.getFilename() 相一致就可以

现在只差一步了,那就是Ctrl + F11,有不当之处敬请提出,共同进步

**
使用javax.mail发邮件代码
**
package cn.cherish.utils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class EmailUtil {
 // properties配置文件地址
 //private static final String PROPERTIES_PATH = "standard_data.properties";
 private static Session session;
 private static Properties props = new Properties();
 private static final String HOST = "smtp.qq.com";
 private static int PORT = 587;
 private static final String isAUTH = "true";
 private static final String FROM = "785427346@qq.com";
 private static final String USERNAME = "785427346@qq.com";
 private static final String PASSWORD = "xxxxxxxxxxxxxxxx";
 private static final String TIMEOUT = "25000";
 private static final String DEBUG = "true";
 // 初始化session
 static {
  props.put("mail.smtp.host", HOST);
  props.put("mail.smtp.port", PORT);
  props.put("mail.smtp.auth", isAUTH);
  props.put("fromer", FROM);
  props.put("username", USERNAME);
  props.put("password", PASSWORD);
  props.put("mail.smtp.timeout", TIMEOUT);
  props.put("mail.debug", DEBUG);
  session = Session.getInstance(props, new Authenticator() {
   @Override
   protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(USERNAME, PASSWORD);
   }
  });
 }
 public static void main(String[] args) {
  try {
   String html = ""+
     ""+
     "爱你"+
     ""+
     "Hello,nice to fuck you!"+
     "并抓了一把你的小鸡鸡"+
     "";
   //sendEmail("785427346@qq.com", "yeah", html, true);
   sendFileEmail("785427346@qq.com", "yeah", html, new File("E:/xiaoming.zip"));
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 
 public static void sendEmail(String to, String title, String content, boolean isHtml)
   throws FileNotFoundException, IOException, MessagingException {
  String fromer = props.getProperty("fromer");
  if (isHtml) {
   sendHtmlEmail(fromer, to, title, content);
  } else {
   sendTextEmail(fromer, to, title, content);
  }
 }
 // 发送纯文字邮件
 public static void sendTextEmail(String from, String to, String subject, String content)
   throws FileNotFoundException, IOException, MessagingException {
  Message message = new MimeMessage(session);
  message.setFrom(new InternetAddress(from));
  message.setRecipient(RecipientType.TO, new InternetAddress(to));
  message.setSubject(subject);
  message.setText(content);
  message.setSentDate(new Date());
  Transport.send(message);
 }
 // 发送有HTML格式邮件
 public static void sendHtmlEmail(String from, String to, String subject, String htmlConent)
   throws FileNotFoundException, IOException, MessagingException {
  Message message = new MimeMessage(session);
  message.setFrom(new InternetAddress(from));
  message.setRecipient(RecipientType.TO, new InternetAddress(to));
  message.setSubject(subject);
  message.setSentDate(new Date());
  Multipart multi = new MimeMultipart();
  BodyPart html = new MimeBodyPart();
  html.setContent(htmlConent, "text/html; charset=utf-8");
  multi.addBodyPart(html);
  message.setContent(multi);
  Transport.send(message);
 }
 // 发送带附件的邮件
 public static void sendFileEmail(String to, String subject, String htmlConent, File attachment)
   throws FileNotFoundException, IOException, MessagingException {
  Message message = new MimeMessage(session);
  String fromer = props.getProperty("fromer");
  message.setFrom(new InternetAddress(fromer));
  message.setRecipient(RecipientType.TO, new InternetAddress(to));
  message.setSubject(subject);
  message.setSentDate(new Date());
  // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
  Multipart multipart = new MimeMultipart();
  // 添加邮件正文
  BodyPart contentPart = new MimeBodyPart();
  contentPart.setContent(htmlConent, "text/html;charset=UTF-8");
  multipart.addBodyPart(contentPart);
  // 添加附件的内容
  if (attachment != null) {
   BodyPart attachmentBodyPart = new MimeBodyPart();
   DataSource source = new FileDataSource(attachment);
   attachmentBodyPart.setDataHandler(new DataHandler(source));
   // 网上流传的解决文件名乱码的方法,其实用MimeUtility.encodeWord就可以很方便的搞定
   // 这里很重要,通过下面的base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
   // sun.misc.base64Encoder enc = new sun.misc.base64Encoder();
   // messageBodyPart.setFileName("=?GBK?B?" +
   // enc.encode(attachment.getName().getBytes()) + "?=");
   // MimeUtility.encodeWord可以避免文件名乱码
   attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
   multipart.addBodyPart(attachmentBodyPart);
  }
  message.setContent(multipart);
  Transport.send(message);
 }
}

总结

以上所述是小编给大家介绍的使用spring框架中的组件发送邮件,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对考高分网网站的支持!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/143338.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号