参考链接:http://www.runoob.com/java/java-sending-email.html

package test.mail;
import com.sun.mail.util.MailSSLSocketFactory; import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.Properties; /**
* @author
* Created by zhen on 2017-11-01.
*/
public class EmailUtil { public static void SendMail(MailConfig mailConfig, MailBody mailBody) throws Exception{ //获取系统属性
Properties properties = System.getProperties(); // 设置邮件服务器
properties.setProperty("mail.smtp.host", mailConfig.getHost()); Authenticator authenticator = null;
if(mailConfig.isAuth()){
//设置进行认证
properties.put("mail.smtp.auth", "true"); //设置认证参数
authenticator = new Authenticator(){
@Override
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(mailConfig.getUserName(), mailConfig.getPassword()); //发件人邮件用户名、密码
}
}; if(mailConfig.isQQ()){ //假如是QQ邮箱
MailSSLSocketFactory sf = new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
properties.put("mail.smtp.ssl.enable", "true");
properties.put("mail.smtp.ssl.socketFactory", sf);
}
} //获取默认的Session对象
Session session = Session.getDefaultInstance(properties, authenticator); //创建默认的MimeMessage对象
MimeMessage message = new MimeMessage(session); // set from: 头部字段
message.setFrom(new InternetAddress(mailConfig.getFrom())); //set To: 头部字段
String[] tos = mailConfig.getTOs();
String[] bccs = mailConfig.getBCCs();
String[] ccs = mailConfig.getCCs();
InternetAddress[] toAddress = new InternetAddress[tos.length];
InternetAddress[] bccAddress = new InternetAddress[bccs.length];
InternetAddress[] ccAddress = new InternetAddress[ccs.length];
for(int i = 0; i < tos.length; i++){
toAddress[i] = new InternetAddress(tos[i]);
}
for(int i = 0; i < bccs.length; i++){
bccAddress[i] = new InternetAddress(bccs[i]);
}
for(int i = 0; i < ccs.length; i++){
ccAddress[i] = new InternetAddress(ccs[i]);
}
message.addRecipients(Message.RecipientType.TO, toAddress);
message.addRecipients(Message.RecipientType.BCC, bccAddress);
message.addRecipients(Message.RecipientType.CC, ccAddress); // set Subject: 头字段
message.setSubject(mailBody.getSubject()); //创建消息部分
BodyPart messageBodyPart = new MimeBodyPart(); //消息
messageBodyPart.setContent(mailBody.getContent(), mailBody.getContentType()); //创建多重消息
Multipart multipart = new MimeMultipart(); //设置消息部分
multipart.addBodyPart(messageBodyPart); //附件部分
for(File attachment : mailBody.getAttachments()){
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachment);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(attachment.getName());
multipart.addBodyPart(messageBodyPart);
} //设置完整消息
message.setContent(multipart); //发送消息
Transport.send(message); } }
class MailConfig{
private String from;
private String[] TOs;
private String[] BCCs;
private String[] CCs;
private String host;
private boolean isAuth;
private String userName;
private String password;
private boolean isQQ; public String getFrom() {
return from;
} public void setFrom(String from) {
this.from = from;
} public String[] getTOs() {
return TOs;
} public void setTOs(String[] TOs) {
this.TOs = TOs;
} public String[] getBCCs() {
return BCCs;
} public void setBCCs(String[] BCCs) {
this.BCCs = BCCs;
} public String[] getCCs() {
return CCs;
} public void setCCs(String[] CCs) {
this.CCs = CCs;
} public String getHost() {
return host;
} public void setHost(String host) {
this.host = host;
} public boolean isAuth() {
return isAuth;
} public void setAuth(boolean auth) {
isAuth = auth;
} public String getUserName() {
return userName;
} public void setUserName(String userName) {
this.userName = userName;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} public boolean isQQ() {
return isQQ;
} public void setQQ(boolean QQ) {
isQQ = QQ;
}
}
class MailBody{
private String subject;
private Object content;
private String contentType;
private File[] attachments; public String getSubject() {
return subject;
} public void setSubject(String subject) {
this.subject = subject;
} public Object getContent() {
return content;
} public void setContent(Object content) {
this.content = content;
} public String getContentType() {
return contentType;
} public void setContentType(String contentType) {
this.contentType = contentType;
} public File[] getAttachments() {
return attachments;
} public void setAttachments(File[] attachments) {
this.attachments = attachments;
}
} package test.mail; import com.sun.mail.util.logging.MailHandler; import java.io.File; import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties; /**
* @author
* Created by zhen on 2017-11-01.
*/
public class SendEmail { public void sendSimpleEmail(String[] args) { //收件人电子邮箱
String to = "18307006930@163.com"; //发件人电子邮箱
String from = "gz961012@126.com"; //指定发送主机
String host = "smtp.126.com"; //获取系统属性
Properties properties = System.getProperties(); // 设置邮件服务器
properties.setProperty("mail.smtp.host", host); //设置进行认证
properties.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(properties, new Authenticator(){
@Override
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("gz961012@126.com", "899496gz"); //发件人邮件用户名、密码
}
}); try{
//创建默认的MimeMessage对象
MimeMessage message = new MimeMessage(session); //set From;头部字段
message.setFrom(new InternetAddress(from)); //set To:头部字段
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); //set Subject: 头部字段
message.setSubject("This is the Subject Line"); //设置消息体
message.setText("This is actual message"); //发送消息
Transport.send(message); }catch (Exception ex) {
ex.printStackTrace();
}
} public void sendHTMLEmail() { //收件人电子邮箱
String to = "18307006930@163.com"; //发件人电子邮箱
String from = "gz961012@126.com"; //指定发送主机
String host = "smtp.126.com"; //获取系统属性
Properties properties = System.getProperties(); // 设置邮件服务器
properties.setProperty("mail.smtp.host", host); //设置进行认证
properties.put("mail.smtp.auth", "true"); //获取默认的Session对象
Session session = Session.getDefaultInstance(properties, new Authenticator(){
@Override
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("gz961012@126.com", "899496gz"); //发件人邮件用户名、密码
}
}); try{
//创建默认的MimeMessage对象
MimeMessage message = new MimeMessage(session); // set from: 头部字段
message.setFrom(new InternetAddress(from)); //set To: 头部字段
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // set Subject: 头字段
message.setSubject("This is the Subject Line!"); //发送HTML消息,可以插入HTML标签
message.setContent("<h1><font color=\"red\">This is actual message</font><h1>", "text/html"); //发送消息
Transport.send(message); }catch(Exception ex) {
ex.printStackTrace();
} } public void sendWithAttachment(String[] args){
//收件人电子邮箱
String to = "18307006930@163.com"; //发件人电子邮箱
String from = "gz961012@126.com"; //指定发送主机
String host = "smtp.126.com"; //获取系统属性
Properties properties = System.getProperties(); // 设置邮件服务器
properties.setProperty("mail.smtp.host", host); //设置进行认证
properties.put("mail.smtp.auth", "true"); //获取默认的Session对象
Session session = Session.getDefaultInstance(properties, new Authenticator(){
@Override
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("gz961012@126.com", "899496gz"); //发件人邮件用户名、密码
}
}); try{
//创建默认的MimeMessage对象
MimeMessage message = new MimeMessage(session); // set from: 头部字段
message.setFrom(new InternetAddress(from)); //set To: 头部字段
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // set Subject: 头字段
message.setSubject("This is the Subject Line!"); //创建消息部分
BodyPart messageBodyPart = new MimeBodyPart(); //消息
messageBodyPart.setContent("<h1><font color=\"red\">This is actual message</font><h1>", "text/html"); //创建多重消息
Multipart multipart = new MimeMultipart(); //设置文本消息部分
multipart.addBodyPart(messageBodyPart); //附件部分
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource("file.txt"); //目录位置为项目的根路径 F:/test/file.txt
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName("file.txt");
multipart.addBodyPart(messageBodyPart); //设置完整消息
message.setContent(multipart); //发送消息
Transport.send(message); }catch(Exception ex) {
ex.printStackTrace();
}
} public static void main(String[] args) {
MailConfig mailConfig = new MailConfig();
mailConfig.setAuth(true);
mailConfig.setHost("smtp.qq.com");
mailConfig.setTOs(new String[]{"18307006930@163.com"});
mailConfig.setBCCs(new String[]{"1580909730@qq.com"});
mailConfig.setCCs(new String[]{});
mailConfig.setUserName("3291984010@qq.com");
mailConfig.setFrom("3291984010@qq.com");
mailConfig.setPassword("ezmfkuhobxtqdbfi");
mailConfig.setQQ(true); MailBody mailBody = new MailBody();
mailBody.setSubject("一封测试邮件");
mailBody.setContent("你好吗?guoDaXia!");
mailBody.setContentType("text/plain;charset=UTF-8");
mailBody.setAttachments(new File[]{new File("file.txt")}); try {
EmailUtil.SendMail(mailConfig, mailBody);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

java发生邮件(转)的更多相关文章

  1. Java发邮件:Java Mail与Apache Mail

    作者:Vinkn 来自http://www.cnblogs.com/Vinkn/ 一.邮件简介 一封邮件由很多信息构成,主要的信息如下,其他的暂时不考虑,例如抄送等: 1.收件人:收件人的邮箱地址,例 ...

  2. Java实现邮件代理发送

    使用java实现邮件发送 首先需要添加jar文件mailapi.jarstmp.jar 1 import java.util.Properties; import javax.mail.Address ...

  3. 用java实现邮件发送验证码

    java实现邮件发送验证码 建议不要用qq邮箱,我使用qq邮箱直接一直给我报530错误,我一直认为我代码写的有错误或者POP3/SMTP服务没弄好.所以建议注册个别的邮箱,我就申请了个网易163邮箱瞬 ...

  4. 回顾2014 Java发生的5件大事

    回顾2014 Java发生的5件大事 1.2月1日:RedMonk分析师确认并宣布Java是最受欢迎和多样化的语言! 2014年,Java生态圈伴随着引擎的轰鸣起步,随着FOSDEM年会的Free J ...

  5. Java 实现邮件的发送

                                             Java 实现邮件的发送 开发邮箱发送功能必须看邮箱方面的资料 改一些东西  (我的是qq 邮箱哟   开通 POP3 ...

  6. java mail邮件发送(带附件) 支持SSL

    java mail邮件发送(带附件)有三个类 MailSenderInfo.java package mail; import java.util.Properties; import java.ut ...

  7. Java实现邮件发送

      概述 Spring Boot下面整合了邮件服务器,使用Spring Boot能够轻松实现邮件发送:整理下最近使用Spring Boot发送邮件和注意事项: Maven包依赖 <depende ...

  8. java spring 邮件发送

    开发中经常会遇到发送邮件进行用户验证,或者其它推送信息的情况,本文基于spring,完成邮件的发送,主要支持普通文本邮件的发送,html文本邮件的发送,带附件的邮件发送,没有实现群发.多个附件发送等需 ...

  9. 【Java EE 学习 21 下】【使用java实现邮件发送、邮件验证】

    一.邮件发送 1.邮件发送使用SMTP协议或者IMAP协议,这里使用SMTP协议演示. SMTP协议使用的端口号:25 rfc821详细记载了该协议的相关信息 (1)使用telnet发送邮件(使用12 ...

随机推荐

  1. SPA (单页应用程序)

    单页Web应用 编辑 单页Web应用(single page web application,SPA),就是只有一张Web页面的应用.单页应用程序 (SPA) 是加载单个HTML 页面并在用户与应用程 ...

  2. C#学习笔记(十二):构造函数、属性和静态类

    面向对象 简写重载的方法:重载中如果逻辑重复的情况下,用参数少的调用参数多 参数空缺,可以用null填补 using System; using System.Collections.Generic; ...

  3. input标签type=button时,如何禁用和开启按钮

    本文为博主原创,未经允许不得转载: <input id="exportCameraButton" type="button" class="bt ...

  4. JS进阶系列之内存空间

    也许很多人像我一样,觉得JS有垃圾回收机制,内存就可以不管了,以至于在全局作用域下定义了很多变量,自以为JS会自动回收,直到最近,看了阮一峰老师,关于javascript内存泄漏的文章时,才发现自己写 ...

  5. PYTHON HTML.PARSER库学习小结--转载

    前段时间,一朋友让我做个小脚本,抓一下某C2C商城上竞争对手的销售/价格数据,好让他可以实时调整自己的营销策略.自己之前也有过写爬虫抓某宝数据的经历,实现的问题不大,于是就答应了.初步想法是利用pyh ...

  6. json 保存

    with open(mpath,"w") as k: dlist=[] for key in yaml_dict["data"]: dlist.append(y ...

  7. django多对多中间表详解

    我们都知道对于ManyToMany字段,Django采用的是第三张中间表的方式.通过这第三张表,来关联ManyToMany的双方.下面我们根据一个具体的例子,详细解说中间表的使用. 一.默认中间表 首 ...

  8. [html]webpack网页开发打包工具

    官方文档:https://webpack.js.org/concepts/ 中文文档:https://doc.webpack-china.org/guides/installation/ 简书简介:h ...

  9. F4+2 团队项目软件设计方案

    目录 1引言 1.1编写目的 1.2背景 1.3定义 1.4参考资料 2总体设计 2.1需求规定 2.2运行环境 2.3基本设计概念和处理流程 2.4功能描述 2.5功能器求与程序的关系 2.6人工处 ...

  10. Codeforces 838A - Binary Blocks(二维前缀和+容斥)

    838A - Binary Blocks 思路:求一下前缀和,然后就能很快算出每一小正方块中1的个数了,0的个数等于k*k减去1的个数,两个的最小值就是要加进答案的值. 代码: #include< ...