原文链接 https://blog.csdn.net/sdaujsj1/article/details/79248469

pom

<!-- https://mvnrepository.com/artifact/javax.mail/mail -->
<!-- 发邮件 -->
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>

bean:

package com.fighting.email;

import java.io.FileInputStream;
import java.util.Properties; import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
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.util.ByteArrayDataSource; public class Mail { private MimeMessage mimeMessage;//Mime邮件对象
private Session session;//邮件会话对象
private Properties properties;//系统属性
private boolean needAuth = false;//smtp是否需要认证
//smtp认证的用户名和密码
private String username;
private String password;
private Multipart multipart;//Multipart对象 邮件内容 标题 附件等内容添加到这里面 然后生成MimeMessage对象 /**
* 构造方法
* @param smtp
*/
public Mail(String smtp){
setSmtpHost(smtp);
createMimeMessage();
} /**
* 创建MimeMessage邮件对象
* @return
*/
public boolean createMimeMessage() {
//获取邮件会话对象
session = Session.getDefaultInstance(properties, null);
//创建Mime邮件对象
mimeMessage = new MimeMessage(session);
multipart = new MimeMultipart();
return true;
} /**
* 设置邮件发送服务器
* @param hostName
*/
public void setSmtpHost(String hostName) {
if (properties==null){
properties=System.getProperties();//获得系统属性对象
}
properties.put("mail.smtp.host",hostName);//设置smtp主机
} /**
* 设置smtp是否需要认证
* @param need
*/
public void setNeedAuth(boolean need){
if (properties == null){
properties = System.getProperties();
}
if (need){
properties.put("mail.smtp.auth","true");
}else {
properties.put("mail.smtp.auth","false");
}
} /**
* 发件人的用户名和密码 163的用户名就是邮箱的前缀
* @param username
* @param password
*/
public void setNamePassword(String username,String password){
this.username = username;
this.password = password;
} /**
* 邮件主题
* @param subject
* @return
*/
public boolean setSubject(String subject){
try {
mimeMessage.setSubject(subject);
return true;
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
} /**
* 邮件正文
* @param mailBody
* @return
*/
public boolean setBody(String mailBody){
BodyPart bodyPart = new MimeBodyPart();
try {
bodyPart.setContent(""+mailBody,"text/html;charset=utf-8");
multipart.addBodyPart(bodyPart);
return true;
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
} /**
* 邮件正文(带图片的)
* @param mailBody
* @param imgFile
* @return
*/
public boolean setBodyWithImg(String mailBody,String imgFile){
BodyPart content = new MimeBodyPart();
BodyPart img = new MimeBodyPart();
try {
multipart.addBodyPart(content);
multipart.addBodyPart(img); ByteArrayDataSource byteArrayDataSource = new ByteArrayDataSource(new FileInputStream(imgFile),"application/octet-stream");
// DataHandler imgDataHandler = new DataHandler(new FileDataSource(imgFile));
DataHandler imgDataHandler = new DataHandler(byteArrayDataSource);
img.setDataHandler(imgDataHandler);
// img.setContent
String imgFilename = imgFile.substring(imgFile.lastIndexOf("/")+1);//图片文件名
//注意:Content-ID的属性值一定要加上<>,不能直接写文件名
String headerValue = "<"+imgFilename+">";
img.setHeader("Content-ID",headerValue);
//为图片设置文件名,有的邮箱会把html内嵌的图片也当成附件
img.setFileName(imgFilename);
//在html代码中要想显示刚才的图片名 src里不能直接写Content-ID的值,要用cid:这种方式
mailBody+="<img src='cid:"+imgFilename+"' alt='picture' width='100px' height='100px' />,骚吗?";
content.setContent(""+mailBody,"text/html;charset=utf-8");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} /**
* 邮件添加附件
* @param file
* @return
*/
public boolean addFileAffix(String file){
String[] fileArray = file.split(","); for (int i = 0; i < fileArray.length; i++) {
FileDataSource fileDataSource = new FileDataSource(fileArray[i]);
try {
BodyPart bodyPart = new MimeBodyPart();
bodyPart.setDataHandler(new DataHandler(fileDataSource));
bodyPart.setFileName(fileDataSource.getName());
multipart.addBodyPart(bodyPart);
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
}
return true;
} /**
* 发件人邮箱
* @param from
* @return
*/
public boolean setFrom(String from){
try {
mimeMessage.setFrom(new InternetAddress(from));
return true;
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
} /**
* 收件人邮箱
* @param to
* @return
*/
public boolean setTo(String to){
if (to==null)
return false;
try {
//电子邮件可以有三种类型的收件人,分别to、cc(carbon copy)和bcc(blind carbon copy),分别是收件人、抄送、密送
mimeMessage.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to));
return true;
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
} /**
* 抄送人邮箱 字符串中逗号分开
* @param copyto
* @return
*/
public boolean setCopyTo(String copyto){
if (copyto == null)
return false;
try {
mimeMessage.setRecipients(Message.RecipientType.CC,(Address[]) InternetAddress.parse(copyto));
return true;
} catch (MessagingException e) {
e.printStackTrace();
return false;
}
} /**
* 发送
* @param copyto
* @return
*/
public boolean sendOut(String copyto){
try {
//multipart放入message
mimeMessage.setContent(multipart);
mimeMessage.saveChanges();
Session mailSession = Session.getInstance(properties, null);
Transport transport = mailSession.getTransport("smtp");
transport.connect(properties.getProperty("mail.smtp.host"),username,password);
transport.sendMessage(mimeMessage,mimeMessage.getRecipients(Message.RecipientType.TO));
if (copyto!=null){
transport.sendMessage(mimeMessage,mimeMessage.getRecipients(Message.RecipientType.CC));
}
System.out.println("邮件发送成功");
transport.close();
return true;
} catch (MessagingException e) {
System.out.println("邮件发送失败");
e.printStackTrace();
return false;
}
} /**
* 该方法调用上边定义的方法 选择性的组合 完成邮件发送
* 普普通通的一对一发送
* @param smtp
* @param from
* @param to
* @param subject
* @param content
* @param username
* @param password
* @return
*/
public static boolean send(String smtp,String from,String to,String subject,
String content,String username,String password){
Mail mail = new Mail(smtp);
mail.setNeedAuth(true);//需要认证
if (!mail.setSubject(subject))
return false;
if (!mail.setBody(content))
return false;
if (!mail.setFrom(from))
return false;
if (!mail.setTo(to)){
return false;
}
mail.setNamePassword(username,password);
if (!mail.sendOut(null))
return false;
return true;
} /**
* 带附件的正文有图片的带有抄送的邮件
* @return
*/
public static boolean sendAndCcWithFile(String smtp,String from,String to,String subject,
String content,String imageFile,String username,String password,String copyto,String filename){
Mail mail = new Mail(smtp);
mail.setNeedAuth(true);//需要认证
if (!mail.setSubject(subject)) {
return false;
}
if (!mail.setBodyWithImg(content,imageFile)) {
return false;
}
if (!mail.addFileAffix(filename))
return false;
if (!mail.setFrom(from)) {
return false;
}
if (!mail.setTo(to)){
return false;
}
if (!mail.setCopyTo(copyto)) {
return false;
}
mail.setNamePassword(username,password);
if (!mail.sendOut(copyto))
return false;
return true;
} }

Test类

package com.fighting.email;

import javax.mail.internet.MimeBodyPart;

public class MailTest {
public static void main(String[] args) {
String smtp ="smtp.qq.com";//SMTP服务器地址
String from = "helloworld6379@qq.com";
String to = "1208286977@qq.com";
String copyto="372528890@qq.com,980301925@qq.com";
String subject = " 狗年大吉";
// String content ="<h1>狗年大吉吧</h1>";
MimeBodyPart img = new MimeBodyPart(); String content ="<div style='color:red;font-size:18px;'>从QQ发来的邮件</div>我这里有一张自拍";
//正文中的图片
String imgFile="E:\\picture\\study\\401.PNG";
//附件
String filename = "E:\\picture\\study\\401.PNG,E:\\picture\\study\\401.PNG";
//163邮箱用户名就是去掉@163.com
String username = "helloworld6379";
String password = "jexbhirasjwifqpx"; // Mail.send(smtp,from,to,subject,content,username,password);
Mail.sendAndCcWithFile(smtp,from,to,subject,content,imgFile,username,password,copyto,filename);
} }

 

password是你开启IMAP/SMTP服务时发来的密码

  

效果:

  

使用jmail发送短信的更多相关文章

  1. PHP发送短信功能

    发送短信的功能主要在于获得短信接口后,在函数中模仿用户行为,例如浏览器跳转输出短信接口的链接. 需要运用的函数为 curl_init(); curl_setopt(); curl_exec(); cu ...

  2. WPF MVVM下做发送短信小按钮

    最近做一个项目,因为涉及到注册,因此需要发送短信,一般发送短信都有一个倒计时的小按钮,因此,就做了一个,在此做个记录. 一.发送消息 没有调用公司的短信平台,只是模拟前台生成一串数字,将此串数字输出一 ...

  3. NetCore 阿里大于发送短信

    使用阿里大于API发送短信,但阿里没有提供NetCore 的API,自己看了下源码重写了发短信这个部分 public class MessageSender { private readonly st ...

  4. android 中调用接口发送短信

    android中可以通过两种方式发送短信 第一:调用系统短信接口直接发送短信:主要代码如下: //直接调用短信接口发短信 SmsManager smsManager = SmsManager.getD ...

  5. Android 学习第13课,android 实现发送短信的功能

    1. 界面布局 界面代码: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" ...

  6. ios调用本地拨打电话,发送短信

    电话.短信是手机的基础功能,iOS中提供了接口,让我们调用.这篇文章简单的介绍一下iOS的打电话.发短信在程序中怎么调用. 1.打电话   [[UIApplication sharedApplicat ...

  7. Android发送短信核心代码

    核心代码:(1)SmsManager manager = SmsManager.getDefault(); //获得默认的消息管理器(2)ArrayList<String> list = ...

  8. Android发送短信

    // 发送短信 public void sendMsg(){ String content = edtSend.getText().toString(); SmsManager smsManager ...

  9. a标签的妙用-拨打电话、发送短信、发送邮件

    前端时间在做手机WAP网站时,遇到需要点击页面上显示的电话号能直接拨号的需求,查找资料发现可以使用html的a标签完美实现该需求!记录下来以备后用...... 目前主流手机浏览器对H5的支持已经很不错 ...

随机推荐

  1. Linux之文件(目录)默认权限、特殊权限与隐藏权限

    文件默认权限 从Linux之用户组.文件权限详解了解到文件与目录的基本权限管理,文件在创建时如果不指定具体的权限,那么系统会给它分配一个默认的权限,这个默认权限就是umask. vbird@Ubunt ...

  2. The query below helps you to locate tables without a primary key:

    SELECT tables.table_schema, tables.table_name, tables.table_rows FROM information_schema.tables LEFT ...

  3. VS2012 安装 NPOI (管理NuGet程序包)

    问题背景 选择项目后右键==>管理NuGet程序包,搜索NPOI,返回服务器无法找到...404 解决方法: 第一步: 访问:https://www.nuget.org/api/v2/      ...

  4. 使用nrm工具高效地管理npm源

    在使用npm时,官方的源下载npm包会比较慢,国内我们基本使用淘宝的源,如果公司内部搭建了一套npm私有仓库,公司内部的源不可能把npm官方的npm包都同步,所以需要切换npm源.如果使用npm/cn ...

  5. apache的bin目录下的apxs有什么作用? PHP模块加载运行方式

    2016-03-26 16:40:28   一个perl脚本安装http server扩展模块用的apxs - APache eXtenSion tool –with-apxs2=/usr/local ...

  6. TCP/IP学习20180630-数据链路层-router choose

    IP路由选择 当一个IP数据包准备好了的时候,IP数据包(或者说是路由器)是如何将数据包送到目的地的呢?它是怎么选择一个合适的路径来"送货"的呢? 最特殊的情况是目的主机和主机直连 ...

  7. python 使用ElementTree解析xml

    以country.xml为例,内容如下: <?xml version="1.0"?> <data> <country name="Liech ...

  8. Ext.NET Grid Group分组使用

    - 需要注意的是, 涉及到分页排序, 最好定义GroupDir 方向与分组方式相同. - 譬如工资表按照最新最前分页输出. 如果分组按照默认排序的话, 最就最前. - 界面呈现出2015年, 2016 ...

  9. Includes() vs indexOf() in JavaScript

    碰到一个问题, 部分机器网页数据源不正常, 简单排查发现是使用了较新的Array.includs 方法. 查了下兼容性, chrome 需要47版本以后支持, 客户机果然是很久的43版本. 用Arra ...

  10. Spark+Scalar+Mysql

    包:mysql-connector-java-5.1.39-bin.jar 平台:Win8.1 环境:MyEclipse2015 hadoop-2.7.3.tar.gz + winutils.exe ...