javaMail 发送成功但是无标题无内容(附带简单实现代码亲测可用)

检查自己的jar 包 从官网下载最新的jar包导入可以解决

我是从下面的连接跟新完jar包之后就好了(点不开请复制链接打开): https://javaee.github.io/javamail/
具体实现步骤如下
1.开启发送邮箱的SMTP功能 并获得授权密码
在这里插入图片描述

2.导入下载的jar包
在这里插入图片描述
3.代码如下:(导入包,改完参数后 可以直接使用 )

public class MailUtils {
    
    

	//参数 email 代表的是注册用户的邮件
	//参数 emailMsg 代表的是发送的信息
	public static void sendMail(String email, String emailMsg)
			throws AddressException, MessagingException, GeneralSecurityException, UnsupportedEncodingException {
    
    
		// 1.创建一个程序与邮件服务器会话对象 Session

		Properties props = new Properties();
		props.setProperty("mail.transport.protocol", "SMTP");
		props.setProperty("mail.host", "smtp.qq.com"); //别的邮箱就用别的
		props.setProperty("mail.smtp.auth", "true");// 指定验证为true
		
		//都说qq要进行ssl加密 但是我没用测试也可以  保险使用还是加上了
		 MailSSLSocketFactory sf = new MailSSLSocketFactory();
	        sf.setTrustAllHosts(true);
	        props.put("mail.smtp.ssl.enable", "true");
	        props.put("mail.smtp.ssl.socketFactory", sf);
		
		// 创建验证器
		Authenticator auth = new Authenticator() {
    
    
			public PasswordAuthentication getPasswordAuthentication() {
    
    
				return new PasswordAuthentication("邮箱名称", "smtp授权密码");
			}
		};

		Session session = Session.getInstance(props, auth);
		session.setDebug(true);  //调试使用可以不用加
		// 2.创建一个Message,它相当于是邮件内容
		Message message = new MimeMessage(session);

		message.setFrom(new InternetAddress("邮箱名称@qq.com","昵称","UTF-8")); // 设置发送者以及昵称

		message.setRecipient(RecipientType.TO, new InternetAddress(email)); // 设置发送方式与接收者

		message.setSubject("邮件标题");


		message.setContent(emailMsg, "text/html;charset=utf-8");

		// 3.创建 Transport用于将邮件发送

		Transport.send(message);
	}
	
	public static void main(String[] args) throws AddressException, MessagingException, GeneralSecurityException, UnsupportedEncodingException {
    
    
		sendMail("测试邮箱@qq.com", "这是一封测试邮件");
	}
	
}

网上好多都是jar包冲突问题 但是我的不是。

如果帮助到你了记得点赞

猜你喜欢

转载自blog.csdn.net/weixin_43423864/article/details/107884229