搜索引擎营销是目前最主要的网站推广营销,个人网上公司注册流程图,如何破解网站后台网址,网站制作中搜索栏怎么做6Java发送邮件#xff1a;使用JavaMail API发送电子邮件
作者#xff1a;Stevedash
发表于#xff1a;2023年8月13日 15点48分
来源#xff1a;Java 发送邮件 | 菜鸟教程 (runoob.com)
电子邮件在现代通信中扮演着至关重要的角色#xff0c;而在Java编程中#xff0c;…Java发送邮件使用JavaMail API发送电子邮件
作者Stevedash
发表于2023年8月13日 15点48分
来源Java 发送邮件 | 菜鸟教程 (runoob.com)
电子邮件在现代通信中扮演着至关重要的角色而在Java编程中我们可以利用JavaMail API来方便地实现发送电子邮件的功能。本篇博客将向您介绍如何使用JavaMail API来发送电子邮件以及一些关键概念和实用示例。 JavaMail API基本概念
JavaMail API是Java平台上用于发送和接收电子邮件的强大库。它提供了一组类和方法可以用于创建、发送和处理电子邮件。使用JavaMail API您可以轻松地在Java应用程序中集成电子邮件功能从而实现诸如发送提醒、通知和报告等任务。 Java 发送邮件
使用Java应用程序发送 E-mail 十分简单但是首先你应该在你的机器上安装 JavaMail API 和Java Activation Framework (JAF) 。
你也可以使用菜鸟教程提供的下载链接
JavaMail mail.jar 1.4.5JAF版本 1.1.1 activation.jar
下载这俩个Jar文件。您需要把 mail.jar 和 activation.jar 文件添加到您的 项目中的lib中然后添加进项目Project Structure➡Libraies➡“”选择上面俩个架包 类型服务器名称服务器地址163为例SSL协议端口非SSL协议端口号TSL协议端口收件服务器POPpop.163.com995110收件服务器IMAPimap.163.com993143发件服务器SMTPsmtp.163.com465/99425587
腾讯企业邮箱服务器地址smtp.exmail.qq.com
腾讯邮箱服务器地址smtp.qq.com
常见问题以及解决办法如下
1、如果出现454 Command not permitted when TLS active 错误请检查你的邮件端口配置的是不是25端口如果是请改成465端口并且需要设置 mail.smtp.starttls.enablefalse即可解决问题。
2、部分邮件提供商smtp登录密码不是账号密码而是授权码务必注意。使用SSL、TLS这个一定要注意。
3、550 用户被锁定普通 163 邮箱是无法通过 smtp.163.com 发送邮件的只有 163 VIP 邮箱才行然后设置 mail.smtp.hostsmtp.vip.163.com
4、550 **Invalid User**from 必须写成带 的邮件格式且 username 要用 前面的
5、553 authentication is required需要设置 mail.smtp.authtrue
步骤概述
以下是使用JavaMail API发送电子邮件的基本步骤
设置邮件服务器属性指定SMTP服务器的主机名、端口、身份验证等属性。创建会话对象使用邮件服务器属性创建一个会话对象同时提供身份验证信息。创建邮件消息创建一个邮件消息对象设置发件人、收件人、主题、内容等信息。发送邮件使用会话对象的Transport类发送邮件消息。
需要用户名密码验证邮件发送实例:
本实例以 QQ 邮件服务器为例你需要在登录QQ邮箱后台在设置》账号中开启POP3/SMTP服务 如下图所示 QQ 邮箱通过生成授权码来设置密码 示例代码
①下面是一个简单的Java程序演示了如何使用JavaMail API发送一封电子邮件
// 导入必要的类
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;public class EmailSender {public static void main(String[] args) {// 设置邮件服务器属性Properties properties new Properties();properties.put(mail.smtp.host, smtp.qq.com); // 设置邮件服务器主机名properties.put(mail.smtp.port, 587); // 设置邮件服务器端口号properties.put(mail.smtp.auth, true); // 启用身份验证properties.put(mail.smtp.starttls.enable, true); // 启用 TLS//properties.put(mail.smtp.socketFactory.port, 465); // 设置 SSL 端口//properties.put(mail.smtp.socketFactory.class, javax.net.ssl.SSLSocketFactory); // 设置 SSL Socket Factory//properties.put(mail.smtp.socketFactory.fallback, false); // 禁用 SSL 回退// 创建会话对象Session session Session.getInstance(properties, new Authenticator() {protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(your_emailexample.com, your_password);// 在这里填写发送邮件的邮箱地址和密码/授权码}});try {// 创建邮件消息Message message new MimeMessage(session);message.setFrom(new InternetAddress(your_emailexample.com)); // 设置发件人邮箱message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipientexample.com)); // 设置收件人邮箱message.setSubject(JavaMail API测试); // 设置邮件主题message.setText(这是一封来自JavaMail API的测试邮件。); // 设置邮件内容// 发送邮件Transport.send(message);System.out.println(邮件发送成功); // 打印成功信息} catch (MessagingException e) {e.printStackTrace(); // 打印异常堆栈信息}}
}
下面是对于参数的描述
type:要被设置为 TO, CC 或者 BCC这里 CC 代表抄送、BCC 代表秘密抄送。举例addresses: 这是 email ID 的数组。在指定电子邮件 ID 时你将需要使用 InternetAddress() 方法。
在 Message.RecipientType 枚举类型中以下几个常量表示不同的收件人类型
TO: 主要收件人这些人将直接收到邮件的副本。CC: 抄送Carbon Copy这些人将收到邮件的副本但这并不是邮件的主要接收者。BCC: 密送Blind Carbon Copy这些人也将收到邮件的副本但其他收件人无法看到他们的地址。
②在使用 JavaMail API 创建邮件消息时您可以通过指定这些收件人类型来将不同的收件人添加到邮件消息中。
例如message.setRecipients(Message.RecipientType.TO, recipientAddresses) 将主要收件人添加到邮件消息中。同样您可以使用相应的常量来添加抄送和密送收件人。
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;public class RecipientTypesExample {public static void main(String[] args) {// 设置邮件服务器属性Properties properties new Properties();properties.put(mail.smtp.host, smtp.example.com);properties.put(mail.smtp.port, 465);properties.put(mail.smtp.auth, true);properties.put(mail.smtp.socketFactory.port, 465);properties.put(mail.smtp.socketFactory.class, javax.net.ssl.SSLSocketFactory);properties.put(mail.smtp.socketFactory.fallback, false);// 创建会话对象Session session Session.getInstance(properties, new Authenticator() {protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(your_emailexample.com, your_password);}});try {// 创建邮件消息Message message new MimeMessage(session);message.setFrom(new InternetAddress(your_emailexample.com));// 添加主要收件人TOAddress[] toRecipients {new InternetAddress(recipient1example.com)};message.setRecipients(Message.RecipientType.TO, toRecipients);// 添加抄送CCAddress[] ccRecipients {new InternetAddress(cc_recipientexample.com)};message.setRecipients(Message.RecipientType.CC, ccRecipients);// 添加密送BCCAddress[] bccRecipients {new InternetAddress(bcc_recipientexample.com)};message.setRecipients(Message.RecipientType.BCC, bccRecipients);message.setSubject(测试邮件收件人类型);message.setText(这是一封测试邮件演示不同的收件人类型。);// 发送邮件Transport.send(message);System.out.println(邮件发送成功);} catch (MessagingException e) {e.printStackTrace();}}
}
③发送一封emil给多个收件人那么使用下面的方法来指定多个收件人ID
void addRecipients(Message.RecipientType type,Address[] addresses) throws MessagingException下面的是具体的代码
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;public class SecureEmailSender {public static void main(String[] args) {// 设置邮件服务器属性Properties properties new Properties();properties.put(mail.smtp.host, smtp.example.com); // 设置邮件服务器主机名properties.put(mail.smtp.port, 465); // 设置邮件服务器端口号properties.put(mail.smtp.auth, true); // 启用身份验证properties.put(mail.smtp.socketFactory.port, 465); // 设置 SSL 端口properties.put(mail.smtp.socketFactory.class, javax.net.ssl.SSLSocketFactory); // 设置 SSL Socket Factoryproperties.put(mail.smtp.socketFactory.fallback, false); // 禁用 SSL 回退// 创建会话对象Session session Session.getInstance(properties, new Authenticator() {protected PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(your_emailexample.com, your_password);// 在这里填写发送邮件的邮箱地址和密码}});try {// 创建邮件消息Message message new MimeMessage(session);message.setFrom(new InternetAddress(your_emailexample.com)); // 设置发件人邮箱// 设置多个收件人邮箱String[] recipients {recipient1example.com, recipient2example.com};Address[] recipientAddresses new Address[recipients.length];for (int i 0; i recipients.length; i) {recipientAddresses[i] new InternetAddress(recipients[i]);}message.setRecipients(Message.RecipientType.TO, recipientAddresses);message.setSubject(JavaMail API测试 - SSL加密); // 设置邮件主题message.setText(这是一封经过SSL加密的测试邮件发送给多个收件人。); // 设置邮件内容// 发送邮件Transport.send(message);System.out.println(邮件发送成功);} catch (MessagingException e) {e.printStackTrace();}}
}
④发送一封HTML E-mail如下
package main.mail邮件Api;// 文件名 SendHTMLEmail.javaimport java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;public class SendHTMLEmail
{public static void main(String [] args){// 收件人电子邮箱String to Stevedashqq.com;// 发件人电子邮箱String from Stevedashqq.com;// 指定发送邮件的主机为 localhostString host smtp.qq.com;// 获取系统属性Properties properties System.getProperties();// 设置邮件服务器properties.setProperty(mail.smtp.host, host);properties.put(mail.smtp.auth, true);// 获取默认session对象Session session Session.getDefaultInstance(properties,new Authenticator(){public PasswordAuthentication getPasswordAuthentication(){return new PasswordAuthentication(Stevedashqq.com, dsadasdasdasda); //发件人邮件用户名、授权码}});try{// 创建默认的 MimeMessage 对象。MimeMessage message new MimeMessage(session);// Set From: 头部头字段message.setFrom(new InternetAddress(from));// Set To: 头部头字段message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));// Set Subject: 头字段/标题头message.setSubject(This is the Subject Line!);// 发送 HTML 消息, 可以插入html标签就是展示出来是页面中的同一个效果message.setContent(h1This is actual message/h1,text/html );// 发送消息Transport.send(message);System.out.println(Sent message successfully....带网页标签效果的);}catch (MessagingException mex) {mex.printStackTrace();}}
}如下图 ⑤发送带附件的邮件
package main.mail邮件Api;// 文件名 SendFileEmail.javaimport java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;public class SendFileEmail
{public static void main(String [] args){// 收件人电子邮箱String to 1207036895qq.com;// 发件人电子邮箱String from 1207036895qq.com;// 指定发送邮件的主机为 localhostString host smtp.qq.com;// 获取系统属性Properties properties System.getProperties();// 设置邮件服务器properties.setProperty(mail.smtp.host, host);properties.put(mail.smtp.auth, true);// 获取默认session对象Session session Session.getDefaultInstance(properties,new Authenticator(){public PasswordAuthentication getPasswordAuthentication(){return new PasswordAuthentication(1207036895qq.com, zzzzzzzzzzzzzzzzzzz); //发件人邮件用户名、授权码}});try{// 创建默认的 MimeMessage 对象。MimeMessage message new MimeMessage(session);// Set From: 头部头字段message.setFrom(new InternetAddress(from));// Set To: 头部头字段message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));// Set Subject: 头字段message.setSubject(This is the Subject Line!);// 创建消息部分BodyPart messageBodyPart new MimeBodyPart();// 消息messageBodyPart.setText(This is message body);// 创建多重消息Multipart multipart new MimeMultipart();// 设置文本消息部分multipart.addBodyPart(messageBodyPart);// 附件部分messageBodyPart new MimeBodyPart();String filename D:/桌面/新建文本文档.txt;DataSource source new FileDataSource(filename);messageBodyPart.setDataHandler(new DataHandler(source));messageBodyPart.setFileName(filename);multipart.addBodyPart(messageBodyPart);// 发送完整消息message.setContent(multipart );// 发送消息Transport.send(message);System.out.println(Sent message successfully....);}catch (MessagingException mex) {mex.printStackTrace();}}
}可以发现有文件名出现乱码
下面修改后的代码解决了编码的问题
package main.mail邮件Api;import java.io.UnsupportedEncodingException;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;public class SendFileEmail1 {public static void main(String[] args) {String to 1207036895qq.com;String from 1207036895qq.com;String host smtp.qq.com;Properties properties System.getProperties();properties.setProperty(mail.smtp.host, host);properties.put(mail.smtp.auth, true);Session session Session.getDefaultInstance(properties, new Authenticator() {public PasswordAuthentication getPasswordAuthentication() {return new PasswordAuthentication(1207036895qq.com, zzzzzzzzzzzzzzzzzzz);}});try {MimeMessage message new MimeMessage(session);message.setFrom(new InternetAddress(from));message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));message.setSubject(这是邮件主题); // 设置邮件主题这里使用中文MimeBodyPart textPart new MimeBodyPart();textPart.setText(这是邮件正文内容); // 设置邮件正文内容这里使用中文MimeBodyPart attachmentPart new MimeBodyPart();String filename D:/桌面/新建文本文档.txt;DataSource source new FileDataSource(filename);attachmentPart.setDataHandler(new DataHandler(source));attachmentPart.setFileName(MimeUtility.encodeText(source.getName())); // 设置附件文件名对文件名进行编码Multipart multipart new MimeMultipart();multipart.addBodyPart(textPart);multipart.addBodyPart(attachmentPart);message.setContent(multipart);Transport.send(message);System.out.println(邮件发送成功);} catch (MessagingException | UnsupportedEncodingException mex) {mex.printStackTrace();}}
}
输出结果如下 注意事项和进阶功能
要保护邮箱安全建议将密码和敏感信息存储在安全的方式中如配置文件或环境变量。JavaMail API还支持更多高级功能如附件、HTML内容、抄送、密送等。您可以根据需要进行扩展。为了避免被邮件服务器标记为垃圾邮件确保邮件内容和行为遵循电子邮件的最佳实践。
总结
JavaMail API为Java程序员提供了发送电子邮件的便捷途径。通过设置邮件服务器属性、创建会话对象以及构建邮件消息我们可以轻松地在Java应用程序中实现电子邮件发送功能。在实际项目中您可以根据不同场景的不同需求采用如附件、HTML内容和抄送等应对。
作者Stevedash
发表于2023年8月13日 15点48分
来源Java 发送邮件 | 菜鸟教程 (runoob.com)
注本文内容基于个人学习理解如有错误或疏漏欢迎指正。感谢阅读如果觉得有帮助请点赞和分享。