使用JavaMail发送邮件

一、准备SMTP登录信息

要使用JavaMail发送邮件,首先需要准备SMTP登录信息。

常用邮件服务商的SMTP信息:

QQ邮箱:SMTP服务器是smtp.qq.com,端口是465/587

163邮箱:SMTP服务器是smtp.163.com,端口是465

Gmail邮箱:SMTP服务器是smtp.gmail.com,端口是465/587

126邮箱:SMTP服务器是smtp,126.com,端口号是25

以126邮箱为例进行邮件的发送:

准备好SMTP登录信息后,把JavaMail相关的依赖jar包导入:javax.mail-162.jar

二、JavaMailUtils工具类

创建一个工具类,该工具类中有一个静态的createSession()方法,此方法用于封装邮箱账号信息,SMTP服务器连接信息,创建Session会话。在后续编写代码发送各种邮件时,不需要重复创建邮箱账号信息等内容,直接调用该工具类中的createSession()方法即可,避免了代码冗余。

//工具类
public final class JavaMailUtils {
	private JavaMailUtils() {}
	public static Session createSession() {
		//邮箱账号信息
				String username="y183296@126.com";  //邮箱发送账号
				String password="NYDGQMMPDAEIGKVQ";//账号授权密码
				//SMTP服务器连接信息
				Properties props=new Properties();
				props.put("mail.smtp.host","smtp.126.com");//SMTP主机名
				props.put("mail.smtp.port","25");//主机端口号
				props.put("mail.smtp.auth","true");//是否需要用户认证
				props.put("mail.smtp.starttls.enable","true");//启用TLS加密
				
				//创建Session会话
				//参数1:smtp服务器连接参数
				//参数2:账号和密码的授权认证对象
				Session session=Session.getInstance(props,new Authenticator() {
					@Override
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(username, password);
					}
				});
				//设置debug模式便于调试
				session.setDebug(true);
		return session;
		
	}
}

三、发送邮件

首先调用工具类的createSession()方法创建session会话,然后创建邮件对象,设置邮件标题、内容、以及发送方和接收方的账号,最后通过Transport.send(message);完成发送。

public class Demo02 {
	public static void main(String[] args) {
		try{
			//1.创建session会话
			Session session=JavaMailUtils.createSession();
			//2.创建邮件对象
			MimeMessage message=new MimeMessage(session);
			message.setSubject("测试邮件");//设置邮件标题
			message.setText("这是一封测试邮件!");//设置内容
			message.setFrom(new InternetAddress("y183296@126.com"));
			message.setRecipient(RecipientType.TO, new InternetAddress("1299542670@qq.com"));
			//3.发送
			Transport.send(message);
        } catch (AddressException e) {
			e.printStackTrace();
		}catch(MessagingException e) {
			e.printStackTrace();
		}
	}

}

四、发送包含HTML标签的邮件

此案例在发送邮件的基础上进行了改动,此案例不仅对一个账号进行了邮件发送,还抄送给了其他两个邮箱。RecipientType.CC设置接收类型为抄送,抄送给的接收方,可以是多人,需要用一个数组来存储InternetAddress[]。邮件正文使用了html标签,message.setText("你被<b>太阳</b>照耀的时候!","utf-8","html");  "utf-8"和"html"可以让带有html标签的字符串能够按html样式正常显示,该案例中"太阳"二字被加粗。

public class Demo03 {
	public static void main(String[] args) {
		try {
			Session session=JavaMailUtils.createSession();
		    MimeMessage message=new MimeMessage(session);
			message.setFrom(new InternetAddress("y183296@126.com"));
			message.setRecipient(RecipientType.TO, new InternetAddress("1299542670@qq.com"));
			message.setRecipients(RecipientType.CC, new InternetAddress[] {new InternetAddress("1423161910@qq.com"),new InternetAddress("2919817636@qq.com")});
			message.setSubject("测试邮件");
			//邮件正文包含html标签
			message.setText("你被<b>太阳</b>照耀的时候!","utf-8","html");
			Transport.send(message);
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		}
			
	}

}

五、发送带有附件的邮件

此案例发送的邮件既包含正文又包含附件,通过BodyPart设置正文和附件,第一个BodyPart是正文,使用setContent()方法设置内容,设置纯文本内容使用textPart.setContent("太阳照耀的时候!","text/plain;charset=utf-8");,设置html文本内容使用textPart.setContent("你被<b>太阳</b>照耀的时候!","text/html;charset=utf-8");。第二个BodyPart是附件,需要设置文件名,并且添加 一个DataHandler(),传入文件的MIME类型。然后构造一个Multipart对象,将正文+附件组装成Multipart对象。最后通过setContent()将Multipart对象放入邮件,即可发送。

public class Demo04 {
	public static void main(String[] args) {
		try {
			Session session=JavaMailUtils.createSession();
		    MimeMessage message=new MimeMessage(session);
			message.setFrom(new InternetAddress("y183296@126.com"));
			message.setRecipient(RecipientType.TO, new InternetAddress("1299542670@qq.com"));
			message.setRecipients(RecipientType.CC, new InternetAddress[] {new InternetAddress("1423161910@qq.com"),new InternetAddress("2919817636@qq.com")});
			message.setSubject("测试邮件");
			//邮件中既包含正文,又包含附件
			//正文
			BodyPart textPart=new MimeBodyPart();
			textPart.setContent("你被<b>太阳</b>照耀的时候!","text/html;charset=utf-8");
			//附件
			BodyPart filePart=new MimeBodyPart();
			filePart.setFileName("图片");
			//上传附件文件
			filePart.setDataHandler(
					new DataHandler(
					new ByteArrayDataSource(
							Files.readAllBytes(Paths.get("D:\\test\\20230706\\bg.jpg")),"application/octet-stream")));
			//将正文+附件组装成Multipart对象
			Multipart multipart=new MimeMultipart();
			multipart.addBodyPart(textPart);
			multipart.addBodyPart(filePart);
			//将Multipart对象放入邮件
			message.setContent(multipart);
			Transport.send(message);
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

}

六、发送内嵌图片的HTML邮件

imagePart.addHeader("Content-ID", "mao");设置了图片的内容ID。contentText.append("<img src=\"cid:mao\"/>");中的cid对应的是图片的内容ID。

public class Demo05 {
	public static void main(String[] args) {
		try {
			Session session=JavaMailUtils.createSession();
		    MimeMessage message=new MimeMessage(session);
			message.setFrom(new InternetAddress("y183296@126.com"));
			message.setRecipient(RecipientType.TO, new InternetAddress("1299542670@qq.com"));
			message.setRecipients(RecipientType.CC, new InternetAddress[] {new InternetAddress("1423161910@qq.com"),new InternetAddress("2919817636@qq.com")});
			message.setSubject("测试邮件mao");
			//邮件正文包含html标签
			BodyPart textPart=new MimeBodyPart();
			StringBuilder contentText=new StringBuilder();
			contentText.append("<h3>小猫</h3>");
			contentText.append("<p>一张小猫图片!</p>");
			contentText.append("<img src=\"cid:mao\"/>");
			textPart.setContent(contentText.toString(),"text/html;charset=utf-8");
			//附件
			BodyPart imagePart=new MimeBodyPart();
			imagePart.setDataHandler(
					new DataHandler(
					new ByteArrayDataSource(
							Files.readAllBytes(Paths.get("D:\\test\\20230706\\bg.jpg")),
							"application/octet-stream")));
			imagePart.addHeader("Content-ID", "mao");//图片的内容ID
			//将正文+附件组装成Multipart对象
			Multipart multipart=new MimeMultipart();
			multipart.addBodyPart(textPart);
			multipart.addBodyPart(imagePart);
			//将Multipart对象放入邮件
			message.setContent(multipart);
			//发送邮件
			Transport.send(message);
		} catch (AddressException e) {
			e.printStackTrace();
		} catch (MessagingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要设置JavaMail发送邮件,你需要按照以下步骤进行操作: 1. 导入相关的类库:首先,确保你的项目中已经导入了JavaMail和Java Activation Framework(JAF)的相关类库。你可以从官方网站(https://javaee.github.io/javamail/)下载并添加这些类库到你的项目中。 2. 配置SMTP服务器信息:你需要指定SMTP服务器的地址和端口号。通常,SMTP服务器的地址是根据你使用邮件服务提供商而不同。例如,对于Gmail来说,SMTP服务器地址是"smtp.gmail.com",端口号是587。 3. 创建Session对象:使用javax.mail.Session类创建一个Session对象。你可以通过使用Properties对象来设置Session的一些属性,例如SMTP服务器信息、是否需要身份验证等。 ```java Properties properties = new Properties(); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("your-email@gmail.com", "your-password"); } }); ``` 在这里,你需要替换`your-email@gmail.com`和`your-password`为你自己的邮箱地址和密码。 4. 创建Message对象:使用javax.mail.Message类创建一个Message对象,并设置邮件发送者、接收者、主题和正文等信息。 ```java Message message = new MimeMessage(session); message.setFrom(new InternetAddress("your-email@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient-email@example.com")); message.setSubject("Hello, World!"); message.setText("This is the content of the email."); ``` 在这里,你需要将`your-email@gmail.com`替换为你自己的邮箱地址,将`recipient-email@example.com`替换为邮件接收者的邮箱地址。 5. 发送邮件使用Transport类的静态方法send()发送邮件。 ```java Transport.send(message); ``` 完整的示例代码如下: ```java import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import java.util.Properties; public class EmailSender { public static void main(String[] args) { Properties properties = new Properties(); properties.put("mail.smtp.host", "smtp.gmail.com"); properties.put("mail.smtp.port", "587"); properties.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("your-email@gmail.com", "your-password"); } }); try { Message message = new MimeMessage(session); message.setFrom(new InternetAddress("your-email@gmail.com")); message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("recipient-email@example.com")); message.setSubject("Hello, World!"); message.setText("This is the content of the email.");

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值