Java Mail
java.mail & javax.mail.internet包。
主要类:
- Session: 邮件会话。
- Store: 邮件存储空间。
- Folder:邮件存储文件夹。
- Message:电子邮件。
- Address:邮件地址。
- Transport:发送协议类。
获取邮件信息:
相关操作见代码:
package tools;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.*;
public class ReceiveMail {
private Session session;
private Store store;
private String username = "ylm_2020@126.com";
private String password = "邮箱登陆密码或在相关获取码";
private String popServer = "pop.126.com";
public void init()throws Exception
{
//设置属性
Properties props = new Properties();
props.put("mail.store.protocol", "pop3");
props.put("mail.imap.class", "com.sun.mail.imap.IMAPStore");
props.put("mail.pop3.class", "com.sun.mail.pop3.POP3Store");
// 创建Session对象
session = Session.getInstance(props,null);
session.setDebug(false); //输出跟踪日志:否
// 创建Store对象
store = session.getStore("pop3");
//连接到收邮件服务器
store.connect(popServer,username,password);
}
public void receiveMessage()throws Exception
{
String folderName = "inbox";
Folder folder=store.getFolder(folderName);
if(folder==null)
{
throw new Exception(folderName+"邮件夹不存在");
}
//打开信箱
folder.open(Folder.READ_ONLY);
System.out.println("您的收件箱有"+folder.getMessageCount()+"封邮件.");
System.out.println("您的收件箱有"+folder.getUnreadMessageCount()+"封未读的邮件.");
//读邮件
Message[] messages=folder.getMessages();
for(int i=1;i<=10;i++)
{
System.out.println("------第"+i+"封邮件-------");
//打印邮件信息
Message message = messages[i];
System.out.println((message.getFrom())[0]);
System.out.println(message.getSubject());
System.out.println();
}
folder.close(false); //关闭邮件夹
}
public void close()throws Exception
{
store.close();
}
public static void main(String[] args)throws Exception {
ReceiveMail client=new ReceiveMail();
//初始化
client.init();
//接收邮件
client.receiveMessage();
//关闭连接
client.close();
}
}
发送邮件:
import javax.mail.*;
import tools.AttachmentMessage;
import tools.HtmlMessage;
import tools.TextMessage;
import java.util.*;
public class GetMail {
private Session session;
private Transport transport;
private String username = "ylm_2020@126.com";
private String password = "邮箱密码或相关验证密码";
private String smtpServer = "smtp.126.com";
public void init()throws Exception
{
//设置属性
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.class", "com.sun.mail.smtp.SMTPTransport");
props.put("mail.smtp.host", smtpServer); //设置发送邮件服务器
props.put("mail.smtp.port", "25");
props.put("mail.smtp.auth", "true"); //SMTP服务器需要身份验证
// 创建Session对象
session = Session.getInstance(props,new Authenticator(){ //验账账户
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
session.setDebug(true); //输出跟踪日志
// 创建Transport对象
transport = session.getTransport();
}
public void sendMessage()throws Exception{
//创建一个邮件
// Message msg = TextMessage.generate();
//Message msg = HtmlMessage.generate();
Message msg = AttachmentMessage.generate();
//发送邮件
transport.connect();
transport.sendMessage(msg, msg.getAllRecipients());
//打印结果
System.out.println("邮件已经成功发送");
}
public void close()throws Exception
{
transport.close();
}
public static void main(String[] args)throws Exception {
GetMail client=new GetMail();
//初始化
client.init();
//发送邮件
client.sendMessage();
//关闭连接
client.close();
}
}
1. 发送一个纯文本文件:
package tools;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class TextMessage {
public static MimeMessage generate() throws AddressException, MessagingException {
String from = "ylm_2020@126.com";
String to = "1072629584@qq.com";//目的邮箱
String subject = "test";
String body = "Hello, it is a letter of encouragement from Peter!";
//创建Session对象
Session session = Session.getDefaultInstance(new Properties());
//创建MIME实例化对象
MimeMessage message = new MimeMessage(session);
//设置发件人
message.setFrom(new InternetAddress(from));
//设置收件人
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
//设置发送日期
message.setSentDate(new Date());
//设置邮件主题
message.setSubject(subject);
//设置纯文本内容邮件正文
message.setText(body);
//保存并生成最终文件内容
message.saveChanges();
return message;
}
}
2. 发送一个含Html内容的邮件:
package tools;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class HtmlMessage {
public static MimeMessage generate() throws AddressException, MessagingException {
String from = "ylm_2020@126.com";
String to = "1694873641@qq.com";//目的邮箱
String subject = "HTML邮件";
String body = "<a href=https://user.qzone.qq.com/1459193124>"
+ "<h4>欢迎访问</h4></a></br>"
+ "<img src=\"http://thirdqq.qlogo.cn/g?b=sdk&k=NY4e7nCKbti"
+ "aiaTmdtoGSypg&s=100&t=1594798694?rand=1597712468\">";
//创建Session对象
Session session = Session.getDefaultInstance(new Properties());
//创建MimeMessage对象
MimeMessage message = new MimeMessage(session);
//设置发件人
message.setFrom(new InternetAddress(from));
//设置收件人
message.setRecipients(Message.RecipientType.TO, to);
//设置邮件标题
message.setSubject(subject);
//设置html邮件正文内容
message.setContent(body, "text/html;charset=gb2312");
//保存并最终生成文件
message.saveChanges();
return message;
}
}
3. 发送一个带有附件的多内容邮件:
package tools;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
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;
public class AttachmentMessage {
public static MimeMessage generate() throws AddressException, MessagingException {
String from = "ylm_2020@126.com";
String to = "1459193124@qq.com";
String subject = "多附件邮件";
String body = "<a href=https://user.qzone.qq.com/1459193124>\" +\n" +
" \"欢迎访问!</a></br>";
//创建Session对象
Session session = Session.getDefaultInstance(new Properties());
//创建MimeMessage对象
MimeMessage message = new MimeMessage(session);
//设置收件人
message.setFrom(new InternetAddress(from));
//设置收件人
message.setRecipients(Message.RecipientType.TO, to);
//设置标题
message.setSubject(subject);
//创建代表邮件正文和附件的各个MimeBoduPart对象
MimeBodyPart contentpart = createBody(body);
MimeBodyPart attachPart1 = createAttach("/Users/kyan/Desktop/photo/weixin/dousen.png");
MimeBodyPart attachPart2 = createAttach("/Users/kyan/Desktop/photo/weixin/monkey.jpg");
//创建用于组合邮件正文和附件的MimeMultipart对象
MimeMultipart allMultipart = new MimeMultipart("mixed");
allMultipart.addBodyPart(contentpart);
allMultipart.addBodyPart(attachPart1);
allMultipart.addBodyPart(attachPart2);
//设置整个邮件内容组合为MimeMultipart对象
message.setContent(allMultipart);
//保存并生成最终文件内容
message.saveChanges();
return message;
}
public static MimeBodyPart createBody(String body) throws MessagingException {
MimeBodyPart mimeBodyPart = new MimeBodyPart();
mimeBodyPart.setContent(body, "text/html;charset=gb2312");
return mimeBodyPart;
}
public static MimeBodyPart createAttach(String fileName) throws MessagingException {
MimeBodyPart Attach = new MimeBodyPart();
FileDataSource fds = new FileDataSource(fileName);
Attach.setDataHandler(new DataHandler(fds));
Attach.setFileName(fds.getName());
return Attach;
}
}
更多操作,多读读其他材料。