闲来无聊学习一个java邮箱。。。
遇到两个比较恶心的问题
1、用QQ服务器发邮件的时候报535的异常,密码也对,服务也开启了,授权码也对,就是发送不出去...结果晚上回家就可以了,不知道为什么...可能是eclipse的问题。
2、在发送带附件和图片混合邮件时,不是所有邮箱都能完整接受,我的win10自带的mail就收不到,网页邮箱和手机邮箱都可以
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.Random;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
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 com.sun.mail.util.MailSSLSocketFactory;
public class EmailMain {
public static void main(String[] args) {
//163邮箱会有垃圾邮件校验,所以我就读取了桌面上的一个文件,随机点内容写进邮件防止被当成恶意邮件
//QQ邮箱
qqEmail(getRandomWord(20), getRandomWord(readTxt("C:\\Users\\ppc\\Desktop\\笔记.txt"),5));
//163邮箱
//email163(getRandomWord(20), getRandomWord(readTxt("C:\\Users\\ppc\\Desktop\\笔记.txt"),5));
}
//把桌面文本写进list中
static LinkedList<String> readTxt(String path){
LinkedList<String> ll = new LinkedList<>();
File file = new File(path);
try {
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8"));
String readContent = null;
while((readContent = br.readLine())!=null) {
if(readContent != "") {
ll.add(readContent);
}
}
br.close();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return ll;
}
//随机num个list中的字符串组成的字符串
static String getRandomWord(List list,int num){
StringBuffer sb = new StringBuffer();
for(int i=0;i<list.size();i++) {
sb.append(list.get(new Random().nextInt(list.size())));
}
return sb.toString();
}
//随机num个字母组成的字符串
static String getRandomWord(int num) {
char[] charArr = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
StringBuffer sb = new StringBuffer();
for(int i=0;i<num;i++) {
sb.append(charArr[new Random().nextInt(charArr.length)]);
}
return sb.toString();
}
//qq邮箱
static void qqEmail(String title,String content) {
// 收件人电子邮箱
String to = "***@***.com";
// 发件人电子邮箱
String from = "****@qq.com";
// 指定发送邮件的主机为 localhost
String host = "smtp.qq.com";
Properties properties = System.getProperties();
//设置邮箱服务器
properties.setProperty("mail.smtp.host", host);
//因为授权码需要验证,开启邮箱验证
properties.put("mail.smtp.auth", "true");
MailSSLSocketFactory sf;
try {
//设置用户名 密码
properties.put("mail.smtp.username", "***@qq.com");
properties.put("mail.smtp.password", "密码");
//设置链接使用的工厂类
properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.smtp.socketFactory.fallback", "false");
//设置端口号
properties.setProperty("mail.smtp.port", "465");
properties.setProperty("mail.smtp.socketFactory.port", "465");
// 获取默认session对象
Session session = Session.getDefaultInstance(properties,new Authenticator(){
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("邮箱", "授权码"); //发件人邮件用户名、授权码
}
});
MimeMessage message = new MimeMessage (session);
//设置邮件发件人
message.setFrom(new InternetAddress(from));
//设置邮件接收人
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: 头部头字段
message.setSubject(title);
//分四种邮件情况
// 纯文本
//message.setContent(content,"text/html;charset=UTF-8");
//文本中带图片
//containsPicture(message);
//带附件
//containsAttachment(message);
//附件、文本中带图片混合
//imageAndAttachment(message);
// }
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void imageAndAttachment(MimeMessage message)
throws MessagingException, UnsupportedEncodingException, IOException, FileNotFoundException {
//正文
MimeBodyPart text = new MimeBodyPart();
text.setContent("xxxx<br/><img src='cid:1.jpg'>","text/html;charset=UTF-8");
//图片
MimeBodyPart image = new MimeBodyPart();
image.setDataHandler(new DataHandler(new FileDataSource("src\\1.jpg")));
image.setContentID("1.jpg");
//附件1
MimeBodyPart attach = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource("src\\2.txt"));
attach.setDataHandler(dh);
attach.setFileName(dh.getName());
//附件2 文件名带汉字
MimeBodyPart attach2 = new MimeBodyPart();
DataHandler dh2 = new DataHandler(new FileDataSource("src\\汉字.txt"));
attach2.setDataHandler(dh2);
attach2.setFileName(MimeUtility.encodeText(dh2.getName()));
//描述关系:正文和图片
MimeMultipart mp1 = new MimeMultipart();
mp1.addBodyPart(text);
mp1.addBodyPart(image);
mp1.setSubType("related");
//描述关系:正文和附件
MimeMultipart mp2 = new MimeMultipart();
mp2.addBodyPart(attach);
mp2.addBodyPart(attach2);
//代表正文的bodypart
MimeBodyPart content2 = new MimeBodyPart();
content2.setContent(mp1);
mp2.addBodyPart(content2);
mp2.setSubType("mixed");
message.setContent(mp2);
message.saveChanges();
message.writeTo(new FileOutputStream("D:\\MixedMail.eml"));
}
private static void containsAttachment(MimeMessage message)
throws MessagingException, IOException, FileNotFoundException {
MimeBodyPart text = new MimeBodyPart();
text.setContent("使用JavaMail创建的带附件的邮件", "text/html;charset=UTF-8");
//创建邮件附件
MimeBodyPart attach = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource("src\\2.txt"));
attach.setDataHandler(dh);
attach.setFileName(dh.getName()); //
//创建容器描述数据关系
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(text);
mp.addBodyPart(attach);
mp.setSubType("mixed");
message.setContent(mp);
message.saveChanges();
//将创建的Email写入到E盘存储
message.writeTo(new FileOutputStream("D:\\attachMail.eml"));
}
private static void containsPicture(MimeMessage message)
throws MessagingException, IOException, FileNotFoundException {
MimeBodyPart text = new MimeBodyPart();
text.setContent("这是一封邮件正文带图片<img src='cid:1.jpg'>的邮件", "text/html;charset=UTF-8");
// 准备图片数据
MimeBodyPart image = new MimeBodyPart();
DataHandler dh = new DataHandler(new FileDataSource("src\\1.jpg"));
image.setDataHandler(dh);
image.setContentID("1.jpg");
// 描述数据关系
MimeMultipart mm = new MimeMultipart();
mm.addBodyPart(text);
mm.addBodyPart(image);
mm.setSubType("related");
message.setContent(mm);
message.saveChanges();
//将创建好的邮件写入到E盘以文件的形式进行保存
message.writeTo(new FileOutputStream("D:\\ImageMail.eml"));
}
//163邮箱 带图片 带附件与qq的相同不做重复介绍
static void email163(String title,String content){
// 收件人电子邮箱
String to = "***@***.com";
// 发件人电子邮箱
String from = "****@163.com";
// 指定发送邮件的主机为 localhost
String host = "smtp.163.com";
Properties properties = System.getProperties();
//设置邮箱服务器
properties.setProperty("mail.smtp.host", host);
//设置验证
properties.put("mail.smtp.auth", "true");
properties.setProperty("mail.user", "****@163.com");
properties.setProperty("mail.password", "*****");
// 获取默认session对象
Session session = Session.getDefaultInstance(properties,new Authenticator(){
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication("****@163.com", "授权码"); //发件人邮件用户名、授权码
}
});
MimeMessage message = new MimeMessage (session);
try {
//设置收件邮箱
message.setFrom(new InternetAddress(from));
//设置接受邮箱
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
// Set Subject: 头部头字段
message.setSubject(title);
// 设置消息体
message.setContent(content,"text/html;charset=UTF-8");
Transport.send(message);
System.out.println("Sent message successfully....");
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
参考文献:https://www.cnblogs.com/xdp-gacl/p/4216311.html