JAVA中发送电子邮件的方法
JAVA中发送邮件的方法不复杂,使用sun的JavaMail的架包就可以实现,也可以使用Spring Boot封装的方法,使用起来更加便捷。
一、下载JavaMail的架包,并导入项目中,如下:
如果是maven项目,maven依赖如下:
- <dependency>
- <groupId>com.sun.mail</groupId>
- <artifactId>javax.mail</artifactId>
- <version>1.5.6</version>
- </dependency>
如果使用spring的方法,还需要导入以下maven依赖:
- <dependency>
- <groupId>org.springframework</groupId>
- <artifactId>spring-context-support</artifactId>
- <version>4.3.6.RELEASE</version>
- </dependency>
二、使用JavaMail发邮件的代码例子,如下:
1、在main函数中对各项参数进行赋值(参数说明已进行备注),即可通过send函数进行发送邮件操作。
- public class TestEmail {
- private final static String TIMEOUT_MS = "20000";
- public static void main(String[] args) {
- String host = "smtp.exmail.qq.com";
- String user = "xxxxxx@qq.com";
- String password = "xxxxxx";
- String recipients = "xxxxxx@qq.com";
- String cc = "";
- String subject = "邮件发送测试";
- String content = "邮件正文:<br>你好!";
- //方式1:通过URL获取附件
- // byte[] attachment = FileUtil.getBytesByUrl("http://127.0.0.1/project/test.pdf");
- //方式2:通过本地路径获取附件
- byte[] attachment = FileUtil.getBytesByFile("c://fujian.pdf");
- String attachmentName = "";
- try {
- attachmentName = MimeUtility.encodeWord("这是附件.pdf");
- send(host, user, password, recipients, cc, subject, content, attachment, attachmentName);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * @param host 邮件服务器主机名
- * @param user 用户名
- * @param password 密码
- * @param recipients 收件人
- * @param cc 抄送人
- * @param subject 主题
- * @param content 内容
- * @param attachment 附件 [没有传 null]
- * @param attachmentName 附件名称 [没有传 null]
- * @throws Exception
- */
- public static void send(final String host, final String user, final String password,
- final String recipients, final String cc, final String subject, final String content,
- final byte[] attachment,final String attachmentName) throws Exception {
- Properties props = new Properties();
- props.put("mail.smtp.host", host);
- props.put("mail.smtp.auth", "true");
- props.put("mail.smtp.timeout", TIMEOUT_MS);
- Authenticator auth = new Authenticator() {
- @Override
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(user, password);
- }
- };
- Session session = Session.getInstance(props, auth);
- MimeMessage msg = new MimeMessage(session);
- msg.setFrom(new InternetAddress(user));
- msg.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));
- if (cc != null && cc.length() > 0) {
- msg.setRecipients(Message.RecipientType.CC, cc);
- }
- msg.setSubject(subject);
- // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
- Multipart multipart = new MimeMultipart();
- // 添加邮件正文
- BodyPart contentPart = new MimeBodyPart();
- contentPart.setContent(content, "text/html;charset=UTF-8");
- multipart.addBodyPart(contentPart);
- // 添加附件的内容
- if (attachment!=null) {
- BodyPart attachmentBodyPart = new MimeBodyPart();
- DataSource source = new ByteArrayDataSource(attachment,"application/octet-stream");
- attachmentBodyPart.setDataHandler(new DataHandler(source));
- //MimeUtility.encodeWord可以避免文件名乱码
- attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachmentName));
- multipart.addBodyPart(attachmentBodyPart);
- }
- // 将multipart对象放到message中
- msg.setContent(multipart);
- // 保存邮件
- msg.saveChanges();
- Transport.send(msg, msg.getAllRecipients());
- }
- }
2、上面的例子中,如果有附件,可对附件进行设置。附件传参类型为byte数组,这里举2个例子,方式1通过网址获取byte数组,如下。方式2通过本地文件获取byte数组。具体可以查看另一篇文章:JAVA中文件与Byte数组相互转换的方法。
- public class FileUtil {
- public static byte[] getBytesByUrl(String urlStr) {
- try {
- URL url = new URL(urlStr);
- HttpURLConnection conn = (HttpURLConnection) url.openConnection();
- InputStream is = conn.getInputStream();
- BufferedInputStream bis = new BufferedInputStream(is);
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- final int BUFFER_SIZE = 2048;
- final int EOF = -1;
- int c;
- byte[] buf = new byte[BUFFER_SIZE];
- while (true) {
- c = bis.read(buf);
- if (c == EOF)
- break;
- baos.write(buf, 0, c);
- }
- conn.disconnect();
- is.close();
- byte[] data = baos.toByteArray();
- baos.flush();
- return data;
- } catch (Exception e) {
- e.printStackTrace();
- }
- return null;
- }
- }
2020-5-26 更新:
三、使用Spring Boot发邮件的代码例子,如下:
- public class MailUtil {
- private static JavaMailSenderImpl javaMailSender;
- private static final String SENDER = "xxxxxx@qq.com";
- static {
- javaMailSender = new JavaMailSenderImpl();
- javaMailSender.setHost("smtp.qq.com");// 链接服务器
- // javaMailSender.setPort(25);// 默认使用25端口发送
- javaMailSender.setUsername("xxxxxx@qq.com");// 邮箱账号
- javaMailSender.setPassword("xxxxxxxxxx");// 授权码
- javaMailSender.setDefaultEncoding("UTF-8");
- // javaMailSender.setProtocol("smtp");
- // Properties properties = new Properties();
- // properties.setProperty("mail.debug", "true");// 启用调试
- // properties.setProperty("mail.smtp.timeout", "1000");// 设置链接超时
- // 设置通过ssl协议使用465端口发送、使用默认端口(25)时下面三行不需要
- // properties.setProperty("mail.smtp.auth", "true");// 开启认证
- // properties.setProperty("mail.smtp.socketFactory.port", "465");// 设置ssl端口
- // properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
- // javaMailSender.setJavaMailProperties(properties);
- }
- public static void main(String[] args) throws Exception {
- sendSimpleMail(new String[]{"xxxxxx@qq.com"}, "邮件主题", "邮件内容", false);
- }
- /**
- * 发送普通邮件
- *
- * @param to 收件人
- * @param subject 主题
- * @param text 正文
- * @param isHtml 正文是否为html格式
- */
- public static void sendSimpleMail(String[] to, String subject, String text, boolean isHtml) throws Exception {
- MimeMessage message = javaMailSender.createMimeMessage();
- MimeMessageHelper helper = new MimeMessageHelper(message, true);
- helper.setFrom(SENDER, "通知");
- helper.setTo(to);
- helper.setSubject(subject);
- helper.setText(text, isHtml);
- javaMailSender.send(message);
- }
- /**
- * 发送带附件邮件
- *
- * @param to 收件人
- * @param subject 主题
- * @param text 正文
- * @param files 附件
- */
- public static void sendAttachmentMail(String[] to, String subject, String text, Map<String, File> files) throws Exception {
- MimeMessage message = javaMailSender.createMimeMessage();
- MimeMessageHelper helper = new MimeMessageHelper(message, true);
- helper.setFrom(SENDER, "通知");
- helper.setTo(to);
- helper.setSubject(subject);
- helper.setText(text);
- Set<Map.Entry<String, File>> fileSet = files.entrySet();
- for (Map.Entry f : fileSet) {
- helper.addAttachment((String) f.getKey(), (File) f.getValue());
- }
- javaMailSender.send(message);
- }
- }
注意12行的password不是你邮箱的登录密码,而是在邮箱中生成的授权码。获取授权码方法如下:
登录QQ邮箱→设置→账户→POP3/IMAP/SMTP/Exchange/CardDAV/CalDAV服务→开启“POP3/SMTP服务”,获取到一个授权码。
JAVA中发送电子邮件的方法的更多相关文章
- 转: "SMTP 服务器无法识别在 Mac 2011 Outlook 中发送电子邮件时错误。错误 17092"
在 Mac 2011 Outlook 中发送电子邮件时,您可能会收到下面的错误消息: 无法发送邮件.SMTP 服务器无法识别任何 Outlook 所支持的身份验证方法.请尝试更改帐户设置中的 SMTP ...
- 在ASP.NET中发送电子邮件的实例教程
首先.导入命名空间: 代码如下 复制代码 using System.Net.Mail; 定义发送电子邮件的方法[网上很多不同的,可以对比着看一下,WinForm的也适用]: 代码如下 复制代码 /// ...
- java中substring的使用方法
java中substring的使用方法 str=str.substring(int beginIndex);截取掉str从首字母起长度为beginIndex的字符串,将剩余字符串赋值给str: str ...
- Java中Set的contains()方法
Java中Set的contains()方法 -- hashCode与equals方法的约定及重写原则 翻译人员: 铁锚 翻译时间: 2013年11月5日 原文链接: Java hashCode() a ...
- mutt+msmtp实现在shell环境中发送电子邮件
作者:邓聪聪 为了自动化接收服务端的文件备份信息,利用mutt+msmtp在shell环境中发送电子邮件,轻松高效的完成运维工作. 下载msmtp wget http://downloads.sour ...
- [java,2017-05-16] java中清空StringBuffer的方法以及耗费时间比较
java中清空StringBuffer的方法,我能想到的有4种: 1. buffer.setLength(0); 设置长度为0 2. buffer.delete(0, buffer.length() ...
- java中BorderLayout的使用方法
相关设置: 使用BorderLayout布局上下左右中布局5个按键,单击中间的那个按键时就关闭窗口 代码: /**** *java中BorderLayout的使用方法 * 使用BorderLayout ...
- 【Java】Java中常用的String方法
本文转载于:java中常用的String方法 1 length()字符串的长度 String a = "Hello Word!"; System.out.println(a.len ...
- Java中Set的contains()方法——hashCode与equals方法的约定及重写原则
转自:http://blog.csdn.net/renfufei/article/details/14163329 翻译人员: 铁锚 翻译时间: 2013年11月5日 原文链接: Java hashC ...
随机推荐
- sqlite ef6 踩坑
调试的时候配置写如下,这样写是没有问题的但是在实际环境中有问题,因为EF路径找不到.会提示错误:The underlying provider failed on open <connectio ...
- 深入理解ES6之—块级绑定
var声明与变量提升 使用var关键字声明的变量,无论其实际声明位置在何处,都会被视为声明于所在函数的顶部(如果声明不在任意函数内,则视为在全局作用域的顶部).这就是所谓的变量提升. 块级声明 块级声 ...
- Chris Richardson微服务翻译:微服务部署
Chris Richardson 微服务系列翻译全7篇链接: 微服务介绍 构建微服务之使用API网关 构建微服务之微服务架构的进程通讯 微服务架构中的服务发现 微服务之事件驱动的数据管理 微服务部署( ...
- 阿里深度兴趣网络模型paper学习
论文地址:Deep Interest Network for Click-Through Rate ... 这篇论文来自阿里妈妈的精准定向检索及基础算法团队.文章提出的Deep Interest Ne ...
- Class对象的创建与使用
类与Class对象 类是程序的一部分,每个类都有一个Class对象,即每当编写并且编译一个新类的时候就会产生一个Class对象.当程序创建第一个对类的静态成员的引用的时候,会将该类动态加载到JVM中, ...
- python 最基本的的单例模型的实现及应用
在我们python开发过程很多 ,在很多地方都会用到单例模式,确保数据的唯一性,最简单的单例模式,我们可以模块导入的方式实现,因为导入文件,无论import多少次 都只导入一次模块. 方法一:装饰器 ...
- java.lang.Class类中的某些方法
反射的代码会经常遇到,Class类中方法真的多,且用的少,大多用在底层源码这块,既然看到了,就记录一下吧,说不定以后厉害了,自己封装框架,haha getComponentType()方法: Syst ...
- js测试地址
很多时候,想写js测试代码,比如在学习的时候.看书敲代码,每次打开VS还是很麻烦的.特别是需要加载一些库的时候. 此时有个工具可以解决: https://jsfiddle.net/ 也是在别人的博客里 ...
- springboot之集成mybatis mongo shiro druid redis jsp
闲来无事,研究一下spingboot 发现好多地方都不一样了,第一个就是官方默认不支持jsp 于是开始狂找资料 终于让我找到了 首先引入依赖如下: <!-- tomcat的支持.--> ...
- 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) ...