java个人邮箱_【更新】Java发送邮件:个人邮箱(QQ & 网易163)+企业邮箱+Android...

本文详细介绍了如何使用Java发送邮件,包括通过企业邮箱(以QQ企业邮箱为例)和个人邮箱(QQ邮箱)的方式。文章提供完整的代码示例,涉及SMTP设置、SSL安全连接以及线程池实现邮件批量发送。同时,对于网易邮箱,文章还指出了授权码的获取和配置步骤。
摘要由CSDN通过智能技术生成

这次把两种情况仔细说一下,因为好多人问啦。

第一种:企业邮箱

这里在这一篇已经说的很清楚了,这次不过是建立个maven工程,引入了最新的javamail依赖,代码优化了一下。直接上代码

pom

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

com.demo

javamail-update

1.0-SNAPSHOT

javax.mail

javax.mail-api

1.6.2

provided

com.sun.mail

javax.mail

1.6.2

org.springframework

spring-core

5.1.8.RELEASE

org.apache.maven.plugins

maven-compiler-plugin

3.8.1

1.8

1.8

CompanyEmail.properties

e.account=***@***.cn

e.pass=***

e.host=smtp.exmail.qq.com

e.port=465

e.protocol=smtp

SendEmailCompanyUtils

package com.demo;

import com.sun.mail.util.MailSSLSocketFactory;

import org.springframework.core.io.support.PropertiesLoaderUtils;

import org.springframework.util.StringUtils;

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.IOException;

import java.io.UnsupportedEncodingException;

import java.security.GeneralSecurityException;

import java.util.Date;

import java.util.Properties;

/**

* 企业邮箱

*/

public class SendEmailCompanyUtils {

private static String account;//登录用户名

private static String pass;//登录密码

private static String host;//服务器地址(邮件服务器)

private static String port;//端口

private static String protocol; //协议

static{

Properties prop = new Properties();

//InputStream instream = ClassLoader.getSystemResourceAsStream("CompanyEmail.properties");//测试环境

try {

//prop.load(instream);//测试环境

prop = PropertiesLoaderUtils.loadAllProperties("CompanyEmail.properties");//生产环境

} catch (IOException e) {

System.out.println("加载属性文件失败");

}

account = prop.getProperty("e.account");

pass = prop.getProperty("e.pass");

host = prop.getProperty("e.host");

port = prop.getProperty("e.port");

protocol = prop.getProperty("e.protocol");

}

static class MyAuthenticator extends Authenticator {

String u = null;

String p = null;

private MyAuthenticator(String u,String p){

this.u=u;

this.p=p;

}

@Override

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(u,p);

}

}

private String to;//收件人

private String subject;//主题

private String content;//内容

private String fileStr;//附件路径

public SendEmailCompanyUtils(String to, String subject, String content, String fileStr) {

this.to = to;

this.subject = subject;

this.content = content;

this.fileStr = fileStr;

}

public void send(){

Properties prop = new Properties();

//协议

prop.setProperty("mail.transport.protocol", protocol);

//服务器

prop.setProperty("mail.smtp.host", host);

//端口

prop.setProperty("mail.smtp.port", port);

//使用smtp身份验证

prop.setProperty("mail.smtp.auth", "true");

//使用SSL,企业邮箱必需!

//开启安全协议

MailSSLSocketFactory sf = null;

try {

sf = new MailSSLSocketFactory();

sf.setTrustAllHosts(true);

prop.put("mail.smtp.ssl.enable", "true");

prop.put("mail.smtp.ssl.socketFactory", sf);

} catch (GeneralSecurityException e1) {

e1.printStackTrace();

}

Session session = Session.getDefaultInstance(prop, new MyAuthenticator(account, pass));

session.setDebug(true);

MimeMessage mimeMessage = new MimeMessage(session);

try {

//发件人

mimeMessage.setFrom(new InternetAddress(account,"XXX"));//可以设置发件人的别名

//mimeMessage.setFrom(new InternetAddress(account));//如果不需要就省略

//收件人

mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

//主题

mimeMessage.setSubject(subject);

//时间

mimeMessage.setSentDate(new Date());

//容器类,可以包含多个MimeBodyPart对象

Multipart mp = new MimeMultipart();

//MimeBodyPart可以包装文本,图片,附件

MimeBodyPart body = new MimeBodyPart();

//HTML正文

body.setContent(content, "text/html; charset=UTF-8");

mp.addBodyPart(body);

//添加图片&附件

if(!StringUtils.isEmpty(fileStr)){

body = new MimeBodyPart();

body.attachFile(fileStr);

mp.addBodyPart(body);

}

//设置邮件内容

mimeMessage.setContent(mp);

//仅仅发送文本

//mimeMessage.setText(content);

mimeMessage.saveChanges();

Transport.send(mimeMessage);

} catch (MessagingException e) {

e.printStackTrace();

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}

CompanySending

package com.demo;

/**

* 发送线程

*/

public class CompanySending implements Runnable {

private String to;//收件人

private String subject;//主题

private String content;//内容

private String fileStr;//附件路径

public CompanySending(String to, String subject, String content, String fileStr) {

this.to = to;

this.subject = subject;

this.content = content;

this.fileStr = fileStr;

}

public void run() {

SendEmailCompanyUtils sendEmail = new SendEmailCompanyUtils(to, subject, content, fileStr);

sendEmail.send();

}

}

CompanySendingPool

package com.demo;

import java.util.concurrent.ArrayBlockingQueue;

import java.util.concurrent.ThreadPoolExecutor;

import java.util.concurrent.TimeUnit;

/**

* 发送线程池

*/

public class CompanySendingPool {

private CompanySendingPool() {

}

private static class Inner{

private static CompanySendingPool instance = new CompanySendingPool();

}

public static CompanySendingPool getInstance(){

return Inner.instance;

}

/**

* 核心线程数:5

* 最大线程数:10

* 时间单位:秒

* 阻塞队列:10

*/

private static ThreadPoolExecutor executor = new ThreadPoolExecutor(

5,

10,

0L,

TimeUnit.SECONDS,

new ArrayBlockingQueue<>(10));

public CompanySendingPool addThread(CompanySending sending){

executor.execute(sending);

return getInstance();

}

public void shutDown(){

executor.shutdown();

}

}

测试

package com.demo;

public class MyTest {

public static void main(String[] args) {

CompanySendingPool pool = CompanySendingPool.getInstance();

pool.addThread(new CompanySending("***@qq.com", "AAA", createEmail().toString(), "file/1.jpg")).shutDown();

}

private static StringBuilder createEmail() {

return new StringBuilder("

快来买桃子

好吃的桃子

桃子含有维生素A、维生素B和维生素C,儿童多吃桃子可使身体健康成长,因为桃子含有的多种维生索可以直接强化他们的身体和智力。

联系桃子:11110000
");

}

}

603529b02d8abf976841e48773daaea2.png

9bca5794a1f32c7f6e2c19996739c2d8.png

第二种:个人邮箱

2431d08f5ff2593ee295d07d4b35875c.png

--

759c20ecbdb0083936199fe9556269c4.png

--

6609d07fc20292cfdb13b5592f3015de.png

--

b46d3291b798f4ceb955ae6507289f13.png

--

178c605c98ace34940bb28e8ca75f495.png

--

记下授权码,一毛钱呢。下面上代码

PersonalEmail.properties

# 发件邮箱

e.account=from@qq.com

# 不需要密码

#e.pass=***

e.host=smtp.qq.com

e.port=25

e.protocol=smtp

# 授权码

e.authorizationCode=fvwmtg***bchb

SendEmailPersonalUtils

package com.demo;

import org.springframework.core.io.support.PropertiesLoaderUtils;

import org.springframework.util.StringUtils;

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.IOException;

import java.io.UnsupportedEncodingException;

import java.util.Date;

import java.util.Properties;

/**

* 关于授权码:https://service.mail.qq.com/cgi-bin/help?subtype=1&&id=28&&no=1001256

* 个人邮箱

*/

public class SendEmailPersonalUtils {

private static String account;//登录用户名

private static String pass;//登录密码

private static String host;//服务器地址(邮件服务器)

private static String port;//端口

private static String protocol; //协议

static{

Properties prop = new Properties();

//InputStream instream = ClassLoader.getSystemResourceAsStream("PersonalEmail.properties");//测试环境

try {

//prop.load(instream);//测试环境

prop = PropertiesLoaderUtils.loadAllProperties("PersonalEmail.properties");//生产环境

} catch (IOException e) {

System.out.println("加载属性文件失败");

}

account = prop.getProperty("e.account");

// 个人邮箱需要授权码,而不是密码。在密码的位置上填写授权码

pass = prop.getProperty("e.authorizationCode");

host = prop.getProperty("e.host");

port = prop.getProperty("e.port");

protocol = prop.getProperty("e.protocol");

}

static class MyAuthenticator extends Authenticator {

String u = null;

String p = null;

private MyAuthenticator(String u,String p){

this.u=u;

this.p=p;

}

@Override

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(u,p);

}

}

private String to;//收件人

private String subject;//主题

private String content;//内容

private String fileStr;//附件路径

public SendEmailPersonalUtils(String to, String subject, String content, String fileStr) {

this.to = to;

this.subject = subject;

this.content = content;

this.fileStr = fileStr;

}

public void send(){

Properties prop = new Properties();

//协议

prop.setProperty("mail.transport.protocol", protocol);

//服务器

prop.setProperty("mail.smtp.host", host);

//端口

prop.setProperty("mail.smtp.port", port);

//使用smtp身份验证

prop.setProperty("mail.smtp.auth", "true");

Session session = Session.getDefaultInstance(prop, new SendEmailPersonalUtils.MyAuthenticator(account, pass));

session.setDebug(true);

MimeMessage mimeMessage = new MimeMessage(session);

try {

//发件人

mimeMessage.setFrom(new InternetAddress(account,"XXX"));//可以设置发件人的别名

//mimeMessage.setFrom(new InternetAddress(account));//如果不需要就省略

//收件人

mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

//主题

mimeMessage.setSubject(subject);

//时间

mimeMessage.setSentDate(new Date());

//容器类,可以包含多个MimeBodyPart对象

Multipart mp = new MimeMultipart();

//MimeBodyPart可以包装文本,图片,附件

MimeBodyPart body = new MimeBodyPart();

//HTML正文

body.setContent(content, "text/html; charset=UTF-8");

mp.addBodyPart(body);

//添加图片&附件

if(!StringUtils.isEmpty(fileStr)){

body = new MimeBodyPart();

body.attachFile(fileStr);

mp.addBodyPart(body);

}

//设置邮件内容

mimeMessage.setContent(mp);

//仅仅发送文本

//mimeMessage.setText(content);

mimeMessage.saveChanges();

Transport.send(mimeMessage);

} catch (MessagingException e) {

e.printStackTrace();

} catch (UnsupportedEncodingException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}

PersonalSending

package com.demo;

/**

* 发送线程

*/

public class PersonalSending implements Runnable {

private String to;//收件人

private String subject;//主题

private String content;//内容

private String fileStr;//附件路径

public PersonalSending(String to, String subject, String content, String fileStr) {

this.to = to;

this.subject = subject;

this.content = content;

this.fileStr = fileStr;

}

public void run() {

SendEmailPersonalUtils sendEmail = new SendEmailPersonalUtils(to, subject, content, fileStr);

sendEmail.send();

}

}

PersonalSendingPool

package com.demo;

import java.util.concurrent.ArrayBlockingQueue;

import java.util.concurrent.ThreadPoolExecutor;

import java.util.concurrent.TimeUnit;

/**

* 发送线程池

*/

public class PersonalSendingPool {

private PersonalSendingPool() {

}

private static class Inner{

private static PersonalSendingPool instance = new PersonalSendingPool();

}

public static PersonalSendingPool getInstance(){

return PersonalSendingPool.Inner.instance;

}

/**

* 核心线程数:5

* 最大线程数:10

* 时间单位:秒

* 阻塞队列:10

*/

private static ThreadPoolExecutor executor = new ThreadPoolExecutor(

5,

10,

0L,

TimeUnit.SECONDS,

new ArrayBlockingQueue<>(10));

public PersonalSendingPool addThread(PersonalSending sending){

executor.execute(sending);

return getInstance();

}

public void shutDown(){

executor.shutdown();

}

}

测试:

package com.demo;

public class MyTest {

public static void main(String[] args) {

PersonalSendingPool pool = PersonalSendingPool.getInstance();

pool.addThread(new PersonalSending("***@qq.com", "BBB", createEmail().toString(), "file/1.jpg")).shutDown();

}

private static StringBuilder createEmail() {

return new StringBuilder("

快来买桃子

好吃的桃子

桃子含有维生素A、维生素B和维生素C,儿童多吃桃子可使身体健康成长,因为桃子含有的多种维生索可以直接强化他们的身体和智力。

联系桃子:11110000
");

}

}

4add8d5f8b6ef1a88a8802ff83a2afc6.png

f47ec04a7d5515920c43e502ac98e333.png

如果是网易邮箱

898129dd1ce5391efe388aba04468ae7.png

进入设置

e3807d5efd4d7296f6fca8d36b93d616.png

点击开启

f576823811d5a3cbc77cab5db5e3ea7b.png

不得不说,网易良心啊,不用短信费,输入正确的验证码之后

7cf8cade65f1233f398299e374fb8246.png

输入授权码(自己定义)

0972cc881848a68435fd4009051be52d.png

到此授权码设置完成。

然后呢,只需要打开PersonalEmail.properties属性文件。修改三个地方即可。

bb93f0899332cbe0762549438b090fa3.png

收到的

4bd07bf225d09516de8809499ad79276.png

第三种:Android(有Android专门支持的jar包)

848024d333f5a92b59750e5ff8f72bb0.png

在中央仓库里也可以看见哦

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值