最近有朋友问邮件怎么发送,就简单写了个demo,因为懒得找jar包,所以项目是创建的maven工程,具体的maven引用的jar如下:

<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.4.4</version>
</dependency> <!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4</version>
</dependency>

然后代码见下:

1、整合demo

因为QQ是https所以中间多了一段,还有就是如果自己搭的邮件服务器可以填写密码,而不用授权码了,这里我是用的QQ邮箱,所以邮箱要先开启SMTP/POP3服务

package com.allan.until;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage; import com.sun.mail.util.MailSSLSocketFactory; public class MailUtil {
private String email;// 收件人邮箱
private String code;// 激活码 public MailUtil(String email, String code) {
this.email = email;
this.code = code;
} public void sendMail() {
// 1.创建连接对象javax.mail.Session
// 2.创建邮件对象 javax.mail.Message
// 3.发送一封激活邮件
String from = "XXX@qq.com";// 发件人电子邮箱
String host = "smtp.qq.com"; // 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易) //Properties properties = System.getProperties();// 获取系统属性
Properties properties =new Properties(); properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
properties.setProperty("mail.smtp.auth", "true");// 打开认证 try {
//QQ邮箱需要下面这段代码,163邮箱不需要
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf); // 1.获取默认session对象
Session session = Session.getDefaultInstance(properties, new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("XXX@qq.com", "XXX"); // 发件人邮箱账号、授权码
}
}); // 2.创建邮件对象
Message message = new MimeMessage(session);
// 2.1设置发件人
message.setFrom(new InternetAddress(from));
// 2.2设置接收人
message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
// 2.3设置邮件主题
message.setSubject("账号激活");
// 2.4设置邮件内容
String content = "验证码:"+ code;
message.setContent(content, "text/html;charset=UTF-8");
// 3.发送邮件
Transport.send(message);
System.out.println("邮件成功发送!");
} catch (Exception e) {
e.printStackTrace();
}
} }

附件版:

package com.aitou.operation.utils;

import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Properties; import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
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.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource; import com.sun.mail.util.MailSSLSocketFactory; public class MailUtil {
/**
*
* 方法名: sendMail
* 描述: 发送邮件
* 创建人: zhangzhuo
* 参数: @param subject
* 参数: @param toMail
* 参数: @param content
* 参数: @param files
* 参数: @return
* 返回类型: boolean
*/
public static boolean sendMail(String fromMail, String password, String subject, String toMail, String content,
List<InputStream> listIs, List<String> listName) {
boolean isFlag = false;
try {
String smtpFromMail = fromMail; //账号
String pwd = password; //密码
String host = "smtp.qq.com"; //端口 Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
//QQ邮箱
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf); Session session = Session.getDefaultInstance(props);
session.setDebug(false); MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(smtpFromMail));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toMail));
message.setSubject(subject);
message.addHeader("charset", "UTF-8"); /*添加正文内容*/
Multipart multipart = new MimeMultipart();
BodyPart contentPart = new MimeBodyPart();
contentPart.setText(content); //contentPart.setHeader("Content-Type", "text/html; charset=UTF-8");
multipart.addBodyPart(contentPart); /*添加附件*/
for (int i = 0; i < listIs.size(); i++) {
MimeBodyPart fileBody = new MimeBodyPart();
DataSource source = new ByteArrayDataSource(listIs.get(i), "application/msexcel");
fileBody.setDataHandler(new DataHandler(source));
String fileName = listName.get(i);
// 中文乱码问题
fileBody.setFileName(MimeUtility.encodeText(fileName));
multipart.addBodyPart(fileBody);
} message.setContent(multipart);
message.setSentDate(new Date());
message.saveChanges();
Transport transport = session.getTransport("smtp"); transport.connect(host, smtpFromMail, pwd);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
isFlag = true;
} catch (Exception e) {
e.printStackTrace();
isFlag = false;
}
} catch (Exception e) {
e.printStackTrace();
}
return isFlag;
}
}

2、spring整合javamail

工具提取:

public class MailUtil {

    /**
* 发送电子邮件
* @param addr 收件人地址
* @param subject 主题
* @param text 内容
* @throws MessagingException
*/
public static void sendMail(String addr,String subject,String text) throws MessagingException{
Properties props=new Properties();
props.put("mail.smtp.host","smtp.sina.com");
props.put("mail.smtp.auth","true");
Session session=Session.getInstance(props);
//构造信息体&nbsp;
MimeMessage message =new MimeMessage(session);
//发件地址&nbsp;
Address address = new InternetAddress("wwwitcastcn@sina.com");
message.setFrom(address);
//收件地址&nbsp;
Address toAddress = new InternetAddress(addr);
message.setRecipient(MimeMessage.RecipientType.TO, toAddress);
//主题&nbsp;
message.setSubject(subject);
//正文&nbsp;
message.setText(text);
message.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect("smtp.sina.com", "wwwitcastcn@sina.com", "itcast"); //发送&nbsp;
transport.sendMessage(message, message.getAllRecipients());
transport.close(); } }

Spring对javamail的支持:

Spring邮件抽象层的主要包为org.springframework.mail。它包括了发送电子邮件的主要接口MailSender,和其对象SimpleMailMessage,它封装了简单邮件的属性如fromto,ccsubject,text。 包里还包含一棵以MailException为根的checked Exception继承树,它们提供了对底层邮件系统异常的高级别抽象。 要获得关于邮件异常层次的更丰富的信息。

为了使用JavaMail中的一些特色, 比如MIME类型的信件, spring提供了MailSender的一个子接口, 即org.springframework.mail.javamail.JavaMailSender。Spring还提供了一个回调接口org.springframework.mail.javamail.MimeMessagePreparator, 用于准备JavaMail的MIME信件。

这里简单的介绍了如何使用spring发送各种形式的邮件以及配置。

1、在src目录下建立mail.properties文件里边包含一下内容

mail.host=smtp.qq.com

mail.username=你的邮箱名
mail.password=你的邮箱密码
mail.from=发送方的邮箱

2、使用spring配置

<?xml version="1.0" encoding="UTF-8"?>

<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- 加载Properties文件 -->
<beanid="configurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<propertyname="locations">
<list>
<value>classpath:mail.properties</value>
</list>
</property>
</bean>
<beanid="mailMessage"class="org.springframework.mail.SimpleMailMessage">
<propertyname="from">
<value>${mail.from}</value>
</property>
<!-- 查看SimpleMailMessage源码还可以注入标题,内容等 -->
</bean>
<!-- 申明JavaMailSenderImpl对象 -->
<beanid="mailSender"class="org.springframework.mail.javamail.JavaMailSenderImpl">
<propertyname="defaultEncoding"value="UTF-8"/>
<propertyname="host"value="${mail.host}"/>
<propertyname="username"value="${mail.username}"/>
<propertyname="password"value="${mail.password}"/>
<propertyname="javaMailProperties">
<props>
<!-- 设置认证开关 -->
<propkey="mail.smtp.auth">true</prop>
<!-- 启动调试开关 -->
<propkey="mail.debug">true</prop>
<!-- 设置发送延时 -->
<propkey="mail.smtp.timeout">0</prop>
</props>
</property>
</bean>
</beans>

3、发送简单邮件

importjavax.mail.MessagingException;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
importorg.springframework.mail.MailSender;
importorg.springframework.mail.SimpleMailMessage;
public class SingleMailSend {
static ApplicationContext actx = new ClassPathXmlApplicationContext("applicationContext.xml");
static MailSender sender = (MailSender) actx.getBean("mailSender");
static SimpleMailMessage mailMessage = (SimpleMailMessage) actx.getBean("mailMessage"); public static void main(String[] args) throws MessagingException {
mailMessage.setSubject("??");
mailMessage.setText("这个是一个通过Spring框架来发送邮件的小程序");
     mailMessage.setTo("XXX@qq.com");
     sender.send(mailMessage);
}
}

4、发送带有图片的邮件,以嵌入HTML的方式

importjava.io.File;
importjavax.mail.MessagingException;
importjavax.mail.internet.MimeMessage;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
importorg.springframework.core.io.FileSystemResource;
importorg.springframework.mail.javamail.JavaMailSenderImpl;
importorg.springframework.mail.javamail.MimeMessageHelper; public class SpringAttachedImageMail { public static voidmain(String[] args) throws MessagingException {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
JavaMailSenderImpl sender = (JavaMailSenderImpl) ctx.getBean("mailSender");
MimeMessage mailMessage = sender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true);
messageHelper.setFrom("9197****1@qq.com");
messageHelper.setTo("9197****1@qq.com");
messageHelper.setSubject("测试邮件中嵌套图片!!");// true 表示启动HTML格式的邮件
messageHelper.setText("<html><head></head><body><h1>hello!!spring image html mail</h1>"
            +"<a href=http://www.baidu.com>baidu</a>"
            + "<img src=cid:image/></body></html>", true);
FileSystemResource img = new FileSystemResource(new File("单.png"));
messageHelper.addInline("image", img);//跟cid一致
sender.send(mailMessage);
System.out.println("邮件发送成功...");
}
}

5、发送带附件的邮件

importjava.io.File; 
importjavax.mail.MessagingException;
importjavax.mail.internet.MimeMessage;
importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;
importorg.springframework.core.io.FileSystemResource;
importorg.springframework.mail.javamail.JavaMailSenderImpl;
importorg.springframework.mail.javamail.MimeMessageHelper; public class SpringAttachedImageMail { public static voidmain(String[] args) throws MessagingException {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
JavaMailSenderImpl sender = (JavaMailSenderImpl) ctx.getBean("mailSender");
MimeMessage mailMessage = sender.createMimeMessage();
MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,true);
messageHelper.setFrom("9197****1@qq.com");
messageHelper.setTo("9197****1@qq.com");
messageHelper.setSubject("测试邮件中嵌套图片!!");// true 表示启动HTML格式的邮件
messageHelper.setText("<html><head></head><body><h1>hello!!spring image html mail</h1>"
            +"<a href=http://www.baidu.com>baidu</a>"
            + "<img src=cid:image/></body></html>", true);
FileSystemResource img = new FileSystemResource(new File("单.png"));
messageHelper.addAttachment("单.png", file);//添加到附件
sender.send(mailMessage);
System.out.println("邮件发送成功...");
}
}

个人备份:

import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
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.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.util.ByteArrayDataSource;
import com.sun.mail.util.MailSSLSocketFactory; public class MailUtil {
/**
*
* 方法名: sendMail
* 描述: 发送邮件
* 创建人: zhangzhuo
* 参数: @param subject
* 参数: @param toMail
* 参数: @param content
* 参数: @param files
* 参数: @return
* 返回类型: boolean
* @throws BaseException
*/
public static boolean sendMail(String fromMail, String password, String subject, String toMail, String content,
List<InputStream> listIs, List<String> listName) throws Exception {
boolean isFlag = false;
String smtpFromMail = fromMail;//账号
String pwd = password; //密码
String host = "smtp.qq.com"; //端口 Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true");
//QQ邮箱
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.smtp.ssl.socketFactory", sf); Session session = Session.getDefaultInstance(props);
session.setDebug(false); MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(smtpFromMail));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toMail));
message.setSubject(subject);
message.addHeader("charset", "UTF-8"); /*添加正文内容*/
Multipart multipart = new MimeMultipart();
BodyPart contentPart = new MimeBodyPart();
contentPart.setText(content); //contentPart.setHeader("Content-Type", "text/html; charset=UTF-8");
multipart.addBodyPart(contentPart); /*添加附件*/
for (int i = 0; i < listIs.size(); i++) {
MimeBodyPart fileBody = new MimeBodyPart();
DataSource source = new ByteArrayDataSource(listIs.get(i), "application/msexcel");
fileBody.setDataHandler(new DataHandler(source));
String fileName = listName.get(i);
// 中文乱码问题
fileBody.setFileName(MimeUtility.encodeText(fileName));
multipart.addBodyPart(fileBody);
} message.setContent(multipart);
message.setSentDate(new Date());
message.saveChanges();
Transport transport = session.getTransport("smtp"); transport.connect(host, smtpFromMail, pwd);
transport.sendMessage(message, message.getAllRecipients());
transport.close();
isFlag = true;
} catch (Exception e) {
e.printStackTrace();
isFlag = false;
}
return isFlag;
}
}

JAVA实用案例之邮件发送的更多相关文章

  1. JAVA实用案例之水印开发

    写在最前面 上周零零碎碎花了一周的时间研究水印的开发,现在终于写了个入门级的Demo,做下笔记同时分享出来供大家参考. Demo是在我上次写的 JAVA实用案例之文件导入导出(POI方式) 框架基础上 ...

  2. JAVA实用案例之图片水印开发

    写在最前面 上周零零碎碎花了一周的时间研究水印的开发,现在终于写了个入门级的Demo,做下笔记同时分享出来供大家参考. Demo是在我上次写的 JAVA实用案例之文件导入导出(POI方式) 框架基础上 ...

  3. JAVA实用案例之文件导出(JasperReport踩坑实录)

    写在最前面 想想来新公司也快五个月了,恍惚一瞬间. 翻了翻博客,因为太忙,也有将近五个多月没认真总结过了. 正好趁着今天老婆出门团建的机会,记录下最近这段时间遇到的大坑-JasperReport. 六 ...

  4. java带图片的邮件发送方法实现

    package sendEmail; import java.util.Properties; import javax.activation.DataHandler; import javax.ac ...

  5. 使用Spring的JAVA Mail支持简化邮件发送(转)

    闲来无事,翻看<Spring in Action>,发现Spring集成了对JAVA Mail的支持,有点小激动的看了一遍,嗯,话说真的简单了很多. Spring的邮件发送的核心是Mail ...

  6. Java 基于javaMail的邮件发送(支持附件)

    基于JavaMail的Java邮件发送Author xiuhong.chen@hand-china.com Desc 简单邮件发送 Date 2017/12/8 项目中需要根据物料资质的状况实时给用户 ...

  7. Java 基于JavaMail的邮件发送

    http://blog.csdn.net/xietansheng/article/details/51673073 http://blog.csdn.net/xietansheng/article/d ...

  8. Java Mail 实现第三方邮件发送功能

    1 创建一个用于发送邮件的类 package com.latiny.service; import java.io.IOException; import java.io.InputStream; i ...

  9. java好用的邮件发送

    1.action代码 // 发送邮件 String strEMAIL = Tools.readTxtFile(Const.EMAIL); //读取邮件配置 String strEM[] = strEM ...

随机推荐

  1. [BZOJ 4720][NOIP 2016] 换教室

    记得某dalao立了"联赛要是考概率期望我直播吃键盘"的$flag$然后就有了这道题233333 4720: [Noip2016]换教室 Time Limit: 20 Sec  M ...

  2. ORACLE 11g 静默安装

    整理下以前的文档,放到博客上面来以后能直接找到. 环境:oracle linux release 6.3 x86_84.oracle 11gR2 一.主机环境配置 1.1 gcc安装 在ISO文件的P ...

  3. cn_office2016

    office 2016是可用激活器激活的,但是激活office 365就有点困难了. 附上office 2016下载地址:http://pan.baidu.com/s/1pLTqPyr 破解机:htt ...

  4. 关于laravel 得手动分页问题

    一般得分页,我们只需要使用paginate方法,就可以简单得搞定.但是遇到数组得组合情况呢?这个时候,就需要我们使用自定义分页了.首先我们看下laravel得分页方法源码: #vendor/larav ...

  5. hdu--1026--Ignatius and the Princess I(bfs搜索+dfs(打印路径))

    Ignatius and the Princess I Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (J ...

  6. 阿里云直播SDK - .NET

    阿里云sdk:https://develop.aliyun.com/sdk/csharp?spm=5176.doc27234.2.4.QiJb9l Github:https://github.com/ ...

  7. python学习===打印时间

    >>> import time >>> print(time.time()) 1501749158.9849465 >>> print(time. ...

  8. 关于JS的DOM操作——重要实例的操作

    1.复选框与按钮的配合使用的DOM操作 <body>                <input type="checkbox" id="ckb1&qu ...

  9. Python 第八天

    文章读写 读写文章是最常见的 IO 操作. 读 1.Python 中内置了open()函数,read()方法以及close()方法来打开文件 fi = open('test.html','r') co ...

  10. 菜鸟之路Vue----一

    Vue api 学习笔记之 全局配置 1.Vue全局配置 Vue.config是一个对象,它包含了Vue的全局变量配置. #silent  用来取消 Vue 所有的日志与警告,其值值类型为布尔值(Bo ...