java实现邮件的发送过程

本文介绍了如何使用Java语言实现邮件的发送,包括邮件发送过程、所需工具如邮件服务器和foxmail,以及关键的activation.jar和mail.jar库。还提供了一个名为MailUtils.java的工具类改写示例和测试主程序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

	这篇只是一个邮件的基本发送过程,不涉及任务调度,不涉及任何框架,只要会安装eclipse开发环境即可测试,后续会学习更高级的,到时候我会进行更新~~~

(1) 邮件发送过程:https://www.cnblogs.com/ysocean/p/7652934.html
在这里插入图片描述
(2)准备工具
a. 邮件服务器
b. 邮件客户端:我用的是foxmail
c. 两个jar包:activation.jar 和mail.jar–这个网上的一位楼主有分享,可以使用,但是我现在找不到了,小伙伴们可以自己尝试找一下,免费的~~
实现找不到的小火把,可以参考这位楼主的:
https://blog.youkuaiyun.com/maximiliansheng/article/details/1927568
d. 工具类:MailUtils.java
(3)MailUtils.java工具类的改写(这是上面的准备工具四,会改写即可以使用):

package com.itheima.mail;
import java.util.Properties;
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.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
public class MailUtils {
	public static void sendMail(String email, String subject,String emailMsg)
			throws AddressException, MessagingException {
		//发送者:tom@163.com 密码是12345
		Properties props = new Properties();
		//发送时需要遵从SMTP协议
		props.setProperty("mail.transport.protocol", "SMTP");
		/*
		 * 发送邮件的域名
		 * props.setProperty("mail.host", "smtp.163.com");:代表是发送给163的用户
		 * props.setProperty("mail.host", "localhost");:代表是发送给本地的用户
		 * 最好是同一后缀名,因为这样会较快
		 */
		props.setProperty("mail.host", "smtp.163.com");
		props.setProperty("mail.smtp.auth", "true");
		Authenticator auth = new Authenticator() {
			public PasswordAuthentication getPasswordAuthentication() {
				//return new PasswordAuthentication("用户名", "密码");
				return new PasswordAuthentication("tom", "12345");
			}
		};
		Session session = Session.getInstance(props, auth);
		
		Message message = new MimeMessage(session);
		message.setFrom(new InternetAddress("tom@163.com"));
		message.setRecipient(RecipientType.TO, new InternetAddress(email)); 
		message.setSubject(subject);
		message.setContent(emailMsg, "text/html;charset=utf-8");
		Transport.send(message);
	}
}

(4) 测试的主程序:

package com.itheima.mail;
public class sendMailTest {
	public static void main(String[] args) throws Exception{
		/**
		 * 这是关于邮件发送的简单入门
		 * 应用:实际中的qq定时发送生日祝福等,定时的效果不在这里进行实现
		 * 		建一个数据库存储信息,调用数据库,设置一个任务调度
		 * 发送者:tom@163.com 密码是12345
		 * 接受者:lucy@163.com
		 */
		/*
		 * sendMail(String email, String subject,String emailMsg)
		 * email:选择发送邮件的地址
		 * subject:主题
		 * emailMsg:信件的内容
		 */
		MailUtils.sendMail("lucy@163.com", "生日祝福", "亲爱的:祝你生日快乐!!!");
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值