JAVA中发送邮件的方法不复杂,使用sun的JavaMail的架包就可以实现,也可以使用Spring Boot封装的方法,使用起来更加便捷。

 一、下载JavaMail的架包,并导入项目中,如下:

如果是maven项目,maven依赖如下:

  1. <dependency>
  2. <groupId>com.sun.mail</groupId>
  3. <artifactId>javax.mail</artifactId>
  4. <version>1.5.6</version>
  5. </dependency>

如果使用spring的方法,还需要导入以下maven依赖:

  1. <dependency>
  2. <groupId>org.springframework</groupId>
  3. <artifactId>spring-context-support</artifactId>
  4. <version>4.3.6.RELEASE</version>
  5. </dependency>

二、使用JavaMail发邮件的代码例子,如下:

1、在main函数中对各项参数进行赋值(参数说明已进行备注),即可通过send函数进行发送邮件操作。

  1. public class TestEmail {
  2.  
  3. private final static String TIMEOUT_MS = "20000";
  4.  
  5. public static void main(String[] args) {
  6. String host = "smtp.exmail.qq.com";
  7. String user = "xxxxxx@qq.com";
  8. String password = "xxxxxx";
  9. String recipients = "xxxxxx@qq.com";
  10. String cc = "";
  11. String subject = "邮件发送测试";
  12. String content = "邮件正文:<br>你好!";
  13. //方式1:通过URL获取附件
  14. // byte[] attachment = FileUtil.getBytesByUrl("http://127.0.0.1/project/test.pdf");
  15. //方式2:通过本地路径获取附件
  16. byte[] attachment = FileUtil.getBytesByFile("c://fujian.pdf");
  17.  
  18. String attachmentName = "";
  19. try {
  20. attachmentName = MimeUtility.encodeWord("这是附件.pdf");
  21. send(host, user, password, recipients, cc, subject, content, attachment, attachmentName);
  22. } catch (Exception e) {
  23. e.printStackTrace();
  24. }
  25. }
  26.  
  27. /**
  28. * @param host 邮件服务器主机名
  29. * @param user 用户名
  30. * @param password 密码
  31. * @param recipients 收件人
  32. * @param cc 抄送人
  33. * @param subject 主题
  34. * @param content 内容
  35. * @param attachment 附件 [没有传 null]
  36. * @param attachmentName 附件名称 [没有传 null]
  37. * @throws Exception
  38. */
  39. public static void send(final String host, final String user, final String password,
  40. final String recipients, final String cc, final String subject, final String content,
  41. final byte[] attachment,final String attachmentName) throws Exception {
  42. Properties props = new Properties();
  43. props.put("mail.smtp.host", host);
  44. props.put("mail.smtp.auth", "true");
  45. props.put("mail.smtp.timeout", TIMEOUT_MS);
  46.  
  47. Authenticator auth = new Authenticator() {
  48. @Override
  49. protected PasswordAuthentication getPasswordAuthentication() {
  50. return new PasswordAuthentication(user, password);
  51. }
  52. };
  53. Session session = Session.getInstance(props, auth);
  54. MimeMessage msg = new MimeMessage(session);
  55. msg.setFrom(new InternetAddress(user));
  56. msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
  57. if (cc != null && cc.length() > 0) {
  58. msg.setRecipients(Message.RecipientType.CC, cc);
  59. }
  60. msg.setSubject(subject);
  61. // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
  62. Multipart multipart = new MimeMultipart();
  63. // 添加邮件正文
  64. BodyPart contentPart = new MimeBodyPart();
  65. contentPart.setContent(content, "text/html;charset=UTF-8");
  66. multipart.addBodyPart(contentPart);
  67. // 添加附件的内容
  68. if (attachment!=null) {
  69. BodyPart attachmentBodyPart = new MimeBodyPart();
  70. DataSource source = new ByteArrayDataSource(attachment,"application/octet-stream");
  71. attachmentBodyPart.setDataHandler(new DataHandler(source));
  72. //MimeUtility.encodeWord可以避免文件名乱码
  73. attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachmentName));
  74. multipart.addBodyPart(attachmentBodyPart);
  75. }
  76. // 将multipart对象放到message中
  77. msg.setContent(multipart);
  78. // 保存邮件
  79. msg.saveChanges();
  80. Transport.send(msg, msg.getAllRecipients());
  81. }
  82. }

2、上面的例子中,如果有附件,可对附件进行设置。附件传参类型为byte数组,这里举2个例子,方式1通过网址获取byte数组,如下。方式2通过本地文件获取byte数组。具体可以查看另一篇文章:JAVA中文件与Byte数组相互转换的方法

  1. public class FileUtil {
  2.  
  3. public static byte[] getBytesByUrl(String urlStr) {
  4. try {
  5. URL url = new URL(urlStr);
  6. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  7. InputStream is = conn.getInputStream();
  8. BufferedInputStream bis = new BufferedInputStream(is);
  9. ByteArrayOutputStream baos = new ByteArrayOutputStream();
  10. final int BUFFER_SIZE = 2048;
  11. final int EOF = -1;
  12. int c;
  13. byte[] buf = new byte[BUFFER_SIZE];
  14. while (true) {
  15. c = bis.read(buf);
  16. if (c == EOF)
  17. break;
  18. baos.write(buf, 0, c);
  19. }
  20. conn.disconnect();
  21. is.close();
  22.  
  23. byte[] data = baos.toByteArray();
  24. baos.flush();
  25. return data;
  26.  
  27. } catch (Exception e) {
  28. e.printStackTrace();
  29. }
  30. return null;
  31. }
  32. }

2020-5-26 更新:

三、使用Spring Boot发邮件的代码例子,如下:

  1. public class MailUtil {
  2.  
  3. private static JavaMailSenderImpl javaMailSender;
  4.  
  5. private static final String SENDER = "xxxxxx@qq.com";
  6.  
  7. static {
  8. javaMailSender = new JavaMailSenderImpl();
  9. javaMailSender.setHost("smtp.qq.com");// 链接服务器
  10. // javaMailSender.setPort(25);// 默认使用25端口发送
  11. javaMailSender.setUsername("xxxxxx@qq.com");// 邮箱账号
  12. javaMailSender.setPassword("xxxxxxxxxx");// 授权码
  13. javaMailSender.setDefaultEncoding("UTF-8");
  14. // javaMailSender.setProtocol("smtp");
  15.  
  16. // Properties properties = new Properties();
  17. // properties.setProperty("mail.debug", "true");// 启用调试
  18. // properties.setProperty("mail.smtp.timeout", "1000");// 设置链接超时
  19. // 设置通过ssl协议使用465端口发送、使用默认端口(25)时下面三行不需要
  20. // properties.setProperty("mail.smtp.auth", "true");// 开启认证
  21. // properties.setProperty("mail.smtp.socketFactory.port", "465");// 设置ssl端口
  22. // properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
  23.  
  24. // javaMailSender.setJavaMailProperties(properties);
  25. }
  26.  
  27. public static void main(String[] args) throws Exception {
  28. sendSimpleMail(new String[]{"xxxxxx@qq.com"}, "邮件主题", "邮件内容", false);
  29. }
  30.  
  31. /**
  32. * 发送普通邮件
  33. *
  34. * @param to 收件人
  35. * @param subject 主题
  36. * @param text 正文
  37. * @param isHtml 正文是否为html格式
  38. */
  39. public static void sendSimpleMail(String[] to, String subject, String text, boolean isHtml) throws Exception {
  40. MimeMessage message = javaMailSender.createMimeMessage();
  41. MimeMessageHelper helper = new MimeMessageHelper(message, true);
  42. helper.setFrom(SENDER, "通知");
  43. helper.setTo(to);
  44. helper.setSubject(subject);
  45. helper.setText(text, isHtml);
  46. javaMailSender.send(message);
  47. }
  48.  
  49. /**
  50. * 发送带附件邮件
  51. *
  52. * @param to 收件人
  53. * @param subject 主题
  54. * @param text 正文
  55. * @param files 附件
  56. */
  57. public static void sendAttachmentMail(String[] to, String subject, String text, Map<String, File> files) throws Exception {
  58. MimeMessage message = javaMailSender.createMimeMessage();
  59. MimeMessageHelper helper = new MimeMessageHelper(message, true);
  60. helper.setFrom(SENDER, "通知");
  61. helper.setTo(to);
  62. helper.setSubject(subject);
  63. helper.setText(text);
  64. Set<Map.Entry<String, File>> fileSet = files.entrySet();
  65. for (Map.Entry f : fileSet) {
  66. helper.addAttachment((String) f.getKey(), (File) f.getValue());
  67. }
  68. javaMailSender.send(message);
  69. }
  70. }

  注意12行的password不是你邮箱的登录密码,而是在邮箱中生成的授权码。获取授权码方法如下:

登录QQ邮箱→设置→账户→POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务→开启“POP3/SMTP服务”,获取到一个授权码。

JAVA中发送电子邮件的方法的更多相关文章

  1. 转: "SMTP 服务器无法识别在 Mac 2011 Outlook 中发送电子邮件时错误。错误 17092"

    在 Mac 2011 Outlook 中发送电子邮件时,您可能会收到下面的错误消息: 无法发送邮件.SMTP 服务器无法识别任何 Outlook 所支持的身份验证方法.请尝试更改帐户设置中的 SMTP ...

  2. 在ASP.NET中发送电子邮件的实例教程

    首先.导入命名空间: 代码如下 复制代码 using System.Net.Mail; 定义发送电子邮件的方法[网上很多不同的,可以对比着看一下,WinForm的也适用]: 代码如下 复制代码 /// ...

  3. java中substring的使用方法

    java中substring的使用方法 str=str.substring(int beginIndex);截取掉str从首字母起长度为beginIndex的字符串,将剩余字符串赋值给str: str ...

  4. Java中Set的contains()方法

    Java中Set的contains()方法 -- hashCode与equals方法的约定及重写原则 翻译人员: 铁锚 翻译时间: 2013年11月5日 原文链接: Java hashCode() a ...

  5. mutt+msmtp实现在shell环境中发送电子邮件

    作者:邓聪聪 为了自动化接收服务端的文件备份信息,利用mutt+msmtp在shell环境中发送电子邮件,轻松高效的完成运维工作. 下载msmtp wget http://downloads.sour ...

  6. [java,2017-05-16] java中清空StringBuffer的方法以及耗费时间比较

    java中清空StringBuffer的方法,我能想到的有4种: 1. buffer.setLength(0);  设置长度为0 2. buffer.delete(0, buffer.length() ...

  7. java中BorderLayout的使用方法

    相关设置: 使用BorderLayout布局上下左右中布局5个按键,单击中间的那个按键时就关闭窗口 代码: /**** *java中BorderLayout的使用方法 * 使用BorderLayout ...

  8. 【Java】Java中常用的String方法

    本文转载于:java中常用的String方法 1 length()字符串的长度 String a = "Hello Word!"; System.out.println(a.len ...

  9. Java中Set的contains()方法——hashCode与equals方法的约定及重写原则

    转自:http://blog.csdn.net/renfufei/article/details/14163329 翻译人员: 铁锚 翻译时间: 2013年11月5日 原文链接: Java hashC ...

随机推荐

  1. sqlite ef6 踩坑

    调试的时候配置写如下,这样写是没有问题的但是在实际环境中有问题,因为EF路径找不到.会提示错误:The underlying provider failed on open <connectio ...

  2. 深入理解ES6之—块级绑定

    var声明与变量提升 使用var关键字声明的变量,无论其实际声明位置在何处,都会被视为声明于所在函数的顶部(如果声明不在任意函数内,则视为在全局作用域的顶部).这就是所谓的变量提升. 块级声明 块级声 ...

  3. Chris Richardson微服务翻译:微服务部署

    Chris Richardson 微服务系列翻译全7篇链接: 微服务介绍 构建微服务之使用API网关 构建微服务之微服务架构的进程通讯 微服务架构中的服务发现 微服务之事件驱动的数据管理 微服务部署( ...

  4. 阿里深度兴趣网络模型paper学习

    论文地址:Deep Interest Network for Click-Through Rate ... 这篇论文来自阿里妈妈的精准定向检索及基础算法团队.文章提出的Deep Interest Ne ...

  5. Class对象的创建与使用

    类与Class对象 类是程序的一部分,每个类都有一个Class对象,即每当编写并且编译一个新类的时候就会产生一个Class对象.当程序创建第一个对类的静态成员的引用的时候,会将该类动态加载到JVM中, ...

  6. python 最基本的的单例模型的实现及应用

    在我们python开发过程很多 ,在很多地方都会用到单例模式,确保数据的唯一性,最简单的单例模式,我们可以模块导入的方式实现,因为导入文件,无论import多少次  都只导入一次模块. 方法一:装饰器 ...

  7. java.lang.Class类中的某些方法

    反射的代码会经常遇到,Class类中方法真的多,且用的少,大多用在底层源码这块,既然看到了,就记录一下吧,说不定以后厉害了,自己封装框架,haha getComponentType()方法: Syst ...

  8. js测试地址

    很多时候,想写js测试代码,比如在学习的时候.看书敲代码,每次打开VS还是很麻烦的.特别是需要加载一些库的时候. 此时有个工具可以解决: https://jsfiddle.net/ 也是在别人的博客里 ...

  9. springboot之集成mybatis mongo shiro druid redis jsp

    闲来无事,研究一下spingboot  发现好多地方都不一样了,第一个就是官方默认不支持jsp  于是开始狂找资料  终于让我找到了 首先引入依赖如下: <!-- tomcat的支持.--> ...

  10. HDU 1002 A + B Problem II(高精度加法(C++/Java))

    A + B Problem II Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others) ...