1.JavaMail的关键对象
Properties:属性对象
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.sina.com.cn");
props.put("mail.smtp.auth", "true");
针对不同的的邮件协议,JavaMail规定了服务提供者必须支持一系列属性,下表是针对SMTP协议的一些常见属性(属性值都以String类型进行设置,属性类型栏仅表示属性是如何被解析的):
属性名 | 属性类型 | 说明 |
---|---|---|
mail.stmp.host | String | SMTP服务器地址,如smtp.sina.com.cn |
mail.stmp.port | int | SMTP服务器端口号,默认为25 |
mail.stmp.auth | boolean | SMTP服务器是否需要用户认证,默认为false |
mail.stmp.user | String | SMTP默认的登陆用户名 |
mail.stmp.from | String | 默认的邮件发送源地址 |
mail.stmp.socketFactory.class | String | socket工厂类类名,通过设置该属性可以覆盖提供者默认的实现,必须实现javax.net.SocketFactory接口 |
mail.stmp.socketFactory.port | int | 指定socket工厂类所用的端口号,如果没有规定,则使用默认的端口号 |
mail.smtp.socketFactory.fallback | boolean | 设置为true时,当使用指定的socket类创建socket失败后,将使用java.net.Socket创建socket,默认为true |
mail.stmp.timeout | int | I/O连接超时时间,单位为毫秒,默认为永不超时 |
2. 生成邮件(需要从邮件服务器中获取)
import java.io.FileOutputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeUtility;
public class EmailReader {
public static void main(String[] args) {
// 邮箱配置
String host = "pop.163.com";
String username = "111@163.com";
String password = "21212";
// 创建连接属性
Properties props = new Properties();
props.put("mail.pop3.host", host);
// 创建会话
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
// 取得pop3协议的邮件服务器
Store store = session.getStore("pop3");
// 连接pop.qq.com邮件服务器
store.connect(host, username, password);
// 打开收件箱
//返回文件夹对象
Folder folder = store.getFolder("INBOX");
//设置仅读
folder.open(Folder.READ_ONLY);
// 读取邮件
Message[] messages = folder.getMessages();
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
// 处理邮件,例如保存为文件
// saveAsEmlFile(message, username+"_" + i + ".eml");
String from = InternetAddress.toString( messages[i].getFrom());
System.out.println("from = " + from);
String s = mimeDecodeString(from);
System.out.println("s = " + s);
String replyTo = InternetAddress.toString( messages[i].getReplyTo());
System.out.println("replyTo = " + replyTo);
String to = InternetAddress.toString( messages[i].getRecipients(Message.RecipientType.TO));
System.out.println("to = " + to);
String subject = messages[i].getSubject();
System.out.println("subject = " + subject);
Date sentDate = messages[i].getSentDate();
System.out.println("sentDate = " + sentDate);
Date receDate = messages[i].getReceivedDate();
System.out.println("receDate = " + receDate);
Enumeration headers = messages[i].getAllHeaders();
System.out.println("headers = " + headers);
}
// 要关闭与 folder 和 store 的连接
// 关闭收件箱和邮件存储
folder.close(false);
store.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 乱码处理
* @param res
* @return
*/
public static String mimeDecodeString(String res) {
if(res != null) {
res = res.trim();
try {
if (res.startsWith("=?GB") || res.startsWith("=?gb")
|| res.startsWith("=?UTF") || res.startsWith("=?utf")) {
res = MimeUtility.decodeText(res);
}
} catch (Exception e) {
System.out.println("乱码处理出错==>" + res+ "<=====>"+e);
}
return res;
}
return null;
}
private static void saveAsEmlFile(Message message, String filename) throws Exception {
// 创建邮件文件
FileOutputStream outputStream = new FileOutputStream(filename);
message.writeTo(outputStream);
outputStream.close();
}
}
3.详细介绍
生成带附件的eml文件,可以使用JavaMail API来实现。JavaMail API是Java平台上用于发送和接收电子邮件的标准API。
4.生成代码(根据业务自己拼接数据生成eml)
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
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;
public class EmlWithAttachment {
public static void main(String[] args) {
// 发送者和接收者的电子邮件地址
String from = "sendr@example.com";
String to = "rever@example.com";
// 邮件主题和正文内容
String subject = "测邮件";
String bodyText = "这带有附件的测试邮件。";
// 附件文件路径
String attachmentPath = "/to/attachment.txt";
// 生成eml文件的路径
String emlFilePath = "/to/generated.eml";
// 设置邮件会话属性
Properties properties = new Properties();
Session session = Session.getDefaultInstance(properties);
try {
// 创建一个新的MimeMessage对象
MimeMessage message = new MimeMessage(session);
// 设置发件人和收件人
message.setFrom(new InternetAddress(from));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
// 设置邮件主题
message.setSubject(subject);
// 创建多部分消息
Multipart multipart = new MimeMultipart();
// 创建文本部分
BodyPart textPart = new MimeBodyPart();
textPart.setText(bodyText);
multipart.addBodyPart(textPart);
// 创建附件部分
BodyPart attachmentPart = new MimeBodyPart();
FileDataSource fileDataSource = new FileDataSource(new File(attachmentPath));
attachmentPart.setDataHandler(new DataHandler(fileDataSource));
attachmentPart.setFileName(fileDataSource.getName());
multipart.addBodyPart(attachmentPart);
// 将多部分消息设置为消息内容
message.setContent(multipart);
// 保存生成的eml文件
try (OutputStream outputStream = new FileOutputStream(new File(emlFilePath))) {
message.writeTo(outputStream);
}
System.out.println("生成带附件的eml文件成功!");
} catch (MessagingException | IOException e) {
e.printStackTrace();
}
}
}
请注意,上述代码需要依赖JavaMail API库。需要在Maven项目中添加以下依赖项来使用JavaMail API:
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.2</version>
</dependency>
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
5.读取eml文件
import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.File;
import java.util.Properties;
public class EMLReader {
public static void main(String[] args) throws Exception {
// 创建Session对象
Properties properties = new Properties();
Session session = Session.getDefaultInstance(properties, null);
// 读取EML文件
File emlFile = new File("email.eml");
MimeMessage message = new MimeMessage(session, new FileInputStream(emlFile));
// 解析邮件内容
String from = message.getFrom()[0].toString();
String to = message.getRecipients(Message.RecipientType.TO)[0].toString();
String subject = message.getSubject();
Date sentDate = message.getSentDate();
String content = getTextFromMimeMultipart((MimeMultipart) message.getContent());
// 输出邮件信息
System.out.println("From: " + from);
System.out.println("To: " + to);
System.out.println("Subject: " + subject);
System.out.println("Sent Date: " + sentDate);
System.out.println("Content: " + content);
}
private static String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws Exception {
int count = mimeMultipart.getCount();
if (count == 0) {
throw new Exception("No message content found.");
}
boolean textFound = false;
String result = "";
for (int i = 0; i < count; i++) {
BodyPart bodyPart = mimeMultipart.getBodyPart(i);
if (bodyPart.isMimeType("text/plain")) {
result = bodyPart.getContent().toString();
textFound = true;
break;
} else if (bodyPart.isMimeType("text/html")) {
result = bodyPart.getContent().toString();
textFound = true;
break;
}
}
if (!textFound) {
throw new Exception("No text content found in the email.");
}
return result;
}
}
报错:
java.lang.ClassCastException: java.lang.String cannot be cast to javax.mail.Multipart at gridnotifierproject_pcbuild.HandleMailInput.retrieveOneMail(HandleMailInput.java:37) at gridnotifierproject_pcbuild.GridNotifierProject_PCBuild.main(GridNotifierProject_PCBuild.java:22)
解决方案:
Object content = msg.getContent();
if (content instanceof String)
{
String body = (String)content;
...
}
else if (content instanceof Multipart)
{
Multipart mp = (Multipart)content;
...
}
发送附件
try {
Session session = JavaMailUtils.createSession();
String text = "我来自于蛮荒,直至存活至公元<b>2111</b>年,这是发给过去的我";
// 2.创建邮件对象(Message抽象类的子类对象)
MimeMessage msg = new MimeMessage(session); // 传入session对象
msg.setFrom(new InternetAddress("zf5209926@163.com")); // 发件人
msg.setRecipient(RecipientType.TO, new InternetAddress("********@qq.com")); // 收件人
msg.setSubject("来自未来的你", "utf-8"); // 标题
// 邮件内容"复合"对象
Multipart multipart = new MimeMultipart();
// 正文
BodyPart textPart = new MimeBodyPart();
// 参数1:正文内容
// 参数2: 内容类型 ; 字符编码集
textPart.setContent(text, "text/html;charset=utf-8");
// 附件
BodyPart imagePart = new MimeBodyPart();
imagePart.setFileName("WSY.jpg");
// 数据处理对象()
imagePart.setDataHandler(new DataHandler(
new ByteArrayDataSource(Files.readAllBytes(Paths.get("C:\\Users\\Pictures\\Saved Pictures\\ya.jpg")),
"application/octet-stream")));
// 添加至邮件内容
multipart.addBodyPart(textPart); // 添加正文
multipart.addBodyPart(imagePart); // 添加附件
// 设置邮件内容
msg.setContent(multipart);
Transport.send(msg);
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
一个Multipart对象可以添加若干个BodyPart,其中第一个BodyPart是文本,即邮件正文,后面的BodyPart是附件。BodyPart依靠setContent()决定添加的内容,如果添加文本,用setContent("...", "text/plain;charset=utf-8")添加纯文本,或者用setContent("...", "text/html;charset=utf-8")添加HTML文本。如果添加附件,需要设置文件名(不一定和真实文件名一致),并且添加一个DataHandler(),传入文件的MIME类型。二进制文件可以用application/octet-stream,Word文档则是application/msword。
最后,通过setContent()把Multipart添加到Message中,即可发送
6. 如果是url格式,想直接转换成附件
URL url=new URL(aaaurl);
DataSource datasource=new URLDataSource(url);
DataHandler datahander=new DataHandler (datasource);
7.可以添加到 添加 Content-Location 头部字段
import java.io.FileOutputStream;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
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;
public class CreateEML {
public static void main(String[] args) {
try {
// 设置邮件会话属性
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
// 创建邮件消息
MimeMessage message = new MimeMessage(session);
// 设置发件人
message.setFrom(new InternetAddress("sender@qq.com"));
// 设置收件人
message.addRecipient(Message.RecipientType.TO, new InternetAddress("recipient@example.com"));
// 设置主题
message.setSubject("测试 EML 文件");
// 创建消息主体
Multipart multipart = new MimeMultipart();
// 添加文本部分
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("这是一个包含附件的测试 EML 文件。", "gb2312");
multipart.addBodyPart(textPart);
// 添加附件部分
MimeBodyPart attachmentPart = new MimeBodyPart();
// attachment.txt 可以是个空文件,只要文件的名字是正确的就OK
DataSource source = new FileDataSource("path/to/your/attachment.txt");
attachmentPart.setDataHandler(new DataHandler(source));
attachmentPart.setFileName("attachment.txt");
// 添加 Content-Location 头部字段
attachmentPart.setHeader("Content-Location", "http://examwwwple.com/attachment.txt");
multipart.addBodyPart(attachmentPart);
// 将消息主体设置到消息中
message.setContent(multipart);
// 保存 EML 文件
FileOutputStream emlFile = new FileOutputStream("path/to/your/message.eml");
message.writeTo(emlFile);
emlFile.close();
System.out.println("EML 文件创建成功。");
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
8.多人的时候,添加
String[] spilt=sss.split(",");
Address[] address=new Address[spilt.length];
for(int i=0;i<spilt.length;i++){
String spt=spilt[i];
address[i]=new InternetAddress(spt);
}
Message.setRecipients(RecipientType.CC,address);