java实现简单的邮件发送

因为做项目要做一个邮件发送功能,所以在网上找了一下资料,现在做一份笔记,给自己备份学习。

做邮箱功能,要先导入一个jar包:javax.mail-1.4.4.jar;这个包可以到maven下载,也可以在我百度网盘下载。

我的百度网盘下载地址是:

链接:https://pan.baidu.com/s/1lzP8CsZsgdmueRZnz-U2fg 密码:1txq

package com.lingshi.email;

import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.junit.Test;

public class TestEmail {
	
	private static Properties props = new Properties();
	private static String MyEmailAccount = "*****@qq.com";
// 重点是这个,这个是在你qq邮箱里开启的一个smtp服务,要自己到qq邮箱开启获取的,而不是qq登录密码
	private static String myEamilPassword = "*****";
	private static String MyEmailSMTPHost = "smtp.qq.com";
	private static String SMTP = "smtp";
	private static int port = 587;
	private static String defaultEncoding = "UTF-8";
	
	static{
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.host", MyEmailSMTPHost);
		props.put("mail.user", MyEmailAccount); 
		props.put("mail.password", myEamilPassword);		
	}
	static Authenticator authenticator = new Authenticator() {  
        @Override  
        protected PasswordAuthentication getPasswordAuthentication() {  
        	// 用户名、密码  
            String userName = props.getProperty("mail.user");  
            String password = props.getProperty("mail.password");  
            return new PasswordAuthentication(userName, password);  
        }  
	};
	
	public static boolean sendEmailCode(String to,String titles,String html) throws MessagingException{
		boolean flag = true;
		Session mailSession = Session.getInstance(props, authenticator);
		MimeMessage message = new MimeMessage(mailSession);
		// 设置发件人
		InternetAddress form = new InternetAddress(props.getProperty("mail.user"));  
		message.setFrom(form);
		// 设置收件人  
		InternetAddress toUser = new InternetAddress(to);  
		message.setRecipient(RecipientType.TO, toUser);
		// 设置邮件标题  
		message.setSubject(titles);    
		// 设置邮件的内容体  
		message.setContent(html, "text/html;charset=UTF-8");    
		// 发送邮件  
		Transport.send(message); 
		return flag;
	}
	
	@Test
	public void testSendEmail() throws MessagingException{
		String to = "*****@qq.com";
		String html = "你接收的验证码为:"+10086+",请你及时回复。";
		String titles = "给你福利";
		boolean flag = sendEmailCode(to,titles,html);
		if(flag){
			System.out.println("发送成功!");
		}else{
			System.out.println("发送失败!");
		}
	}
}

注意:

①:MyEmailAccount:是自己的邮箱;

③:myEamilPassword:是一个qq邮箱的smtp服务秘钥,需要自己到qq邮箱启动(具体启动步骤可以百度);

②:to:是要发送到朋友的邮箱;

这样一个简单的邮件发送功能已经完成。谢谢各位客官观看。

猜你喜欢

转载自blog.csdn.net/chenxihua1/article/details/81315570
今日推荐