原文链接 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. Synchronized 有几种用法?

    我们都知道 Synchronized 是线程安全同步用的,大部分程序可能只会用到同步方法上面.其实 Synchronized 可以用到更多的场合. 1.同步普通方法(锁实例对象) 这个也是我们用得最多 ...

  2. 谈谈 ServerFul 架构

    我写了一篇文章 <自己实现一个线程池>  https://www.cnblogs.com/KSongKing/p/9803935.html , 其实 不仅仅 是 线程池, 中间件 层 的 ...

  3. 光速搭lvs + keepalived + nginx

    环境:   VIP         192.168.2.224 LVS        192.168.2.217     centos7 nginx1    192.168.2.231     cen ...

  4. python unittest setUp 和 setUpClass 区别

    import unittest class Test(unittest.TestCase): def setUp(self): print("start!=======") def ...

  5. 阅读 video on-screen display v6.0笔记

    阅读 video on-screen display v6.0笔记 关于axi总线时钟的区分 需要弄清楚的是aclk, aclken, aresetn 信号是和video 有关的,axi4-lite的 ...

  6. python成功之道

    https://blog.ansheng.me/article/python-full-stack-way

  7. 常量&字符编码

    day1 name='Nod Chen' name2=name print('My name is ',name,name2) name='Luna zhou' print(name,name2) _ ...

  8. inode引起的Linux无法创建新文件,磁盘空间不足

    df -h,判断硬盘空间是否已经满了,占用率达100% ,就可以断定该分区满了. df -ia,占用率达100%,也会导致无法创建新文件.一般都是存在大量小文件引起的. inode包含文件的元信息,具 ...

  9. dns缓存刷新时间是多久?dns本地缓存时间介绍

    原文: http://www.winwin7.com/JC/4742.html dns缓存刷新时间是多久?一般来说,我们只知道DNS解析是互联网绝大多数应用的实际寻址方式,在我们打开某站点,DNS返回 ...

  10. (转)查看SQLServer最耗资源时间的SQL语句

    原文地址:https://www.cnblogs.com/My-Dream/p/6270308.html 1.找出执行时间最长的10条SQL(适用于SQL SERVER 2005及其以上版本) SEL ...