作者:0o可人儿o0_962 | 来源:互联网 | 2023-09-13 10:07
篇首语:本文由编程笔记#小编为大家整理,主要介绍了javaweb网页实现邮箱发送相关的知识,希望对你有一定的参考价值。
网页邮件传输
邮箱的传输原理
导入相关依赖
<dependency>
<groupId>javax.activationgroupId>
<artifactId>activationartifactId>
<version>1.1.1version>
dependency>
<dependency>
<groupId>javax.mailgroupId>
<artifactId>javax.mail-apiartifactId>
<version>1.4.7version>
dependency>
获取QQ的授权码
点击进入QQ邮箱
点击设置&#xff0c;往下拉&#xff0c;直到看见pop3等各种服务&#xff0c;开启pop3/STMP服务
文本邮件的发送
Properties prop&#61;new Properties();
prop.setProperty("mail.host","smtp.qq.com");
prop.setProperty("mail.transport.protocol","smtp");
prop.setProperty("mail.smtp.auth","true");
MailSSLSocketFactory sf&#61;new MailSSLSocketFactory();
sf.setTrustAllHosts(true);
prop.put("mail.smtp.ssl.enable","true");
prop.put("mail.smtp.ssl.socketFactory",sf);
- 创建session对象
Session session&#61;Session.getDefaultInstance(prop, new Authenticator()
&#64;Override
protected PasswordAuthentication getPasswordAuthentication()
return new PasswordAuthentication("XXXX&#64;qq.com","授权码");
);
session.setDebug(true);
- 通过session得到transport对象
Transport ts&#61;session.getTransport();
- 通过用户名和授权码连接邮箱
ts.connect("smtp.qq.com","XXXX&#64;qq.com","授权码");
- 创建邮箱
MimeMessage message&#61;new MimeMessage(session);
message.setFrom(new InternetAddress("XXXX&#64;qq.com"));
message.setRecipient(Message.RecipientType.TO,new InternetAddress("XXXX&#64;qq.com"));
message.setSubject("发送的标题");
message.setContent("内容","text/html;charset&#61;UTF-8");
- 发送邮箱
ts.sendMessage(message,message.getAllRecipients());
ts.close();
邮箱发送图片
只需要更改创建邮箱的文本内容&#xff0c;设置成为图片等资源可以发送的模式
MimeBodyPart image&#61;new MimeBodyPart();
DataHandler dh&#61;new DataHandler(new FileDataSource("D:\\\\Bert\\\\1594126632(1).jpg"));
image.setDataHandler(dh);
image.setContentID("bz.jpg");
MimeBodyPart text&#61;new MimeBodyPart();
text.setContent("这是一张正文","text/html;charset&#61;UTF-8");
MimeMultipart mm&#61;new MimeMultipart();
mm.addBodyPart(text);
mm.addBodyPart(image);
mm.setSubType("related");
message.setContent(mm);
message.saveChanges();
邮箱发送附件
在邮箱发送图片的地方多增加一个发送附件的方法
MimeBodyPart body1&#61; new MimeBodyPart();
body1.setDataHandler(new DataHandler(new FileDataSource("D:\\\\Bert\\\\cmd.txt")));
body1.setFileName("1.txt");
MimeMultipart mm&#61;new MimeMultipart();
mm.addBodyPart(body1);
mm.addBodyPart(text);