Java发送简单邮箱

Java发送简单邮箱

话不多说,直接上代码带注释,首先需要引入一个jar包(我是这个版本):javax.mail-1.6.2.jar.,

package java_mail;

import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**javaMail*/
public class JavaMailDemo {
	public static void main(String[] args) throws Exception{
		Properties props= new Properties();
		props.setProperty("mail.transport.protocol", "smtp");	//使用smtp协议
		props.setProperty("mail.smtp.host", "smtp.qq.com");		//qq邮箱协议地址
		props.setProperty("mail.smtp.port", "465");				//qq邮箱协议端口号
		props.setProperty("mail.smtp.auth", "true");			//授权
		
		//QQ邮箱:SSL安全认证(使用类javax.net.ssl.SSLSocketFactory支持)
		props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		//是否处理非 SSL认证的请求
		props.setProperty("mail.smtp.socketFactory.fallback", "false");
		//SSL端口号(与QQ邮箱端口一致)
		props.setProperty("mail.smtp.socketFactory.port", "465");
		
		
		Session session = Session.getInstance(props);
		session.setDebug(true); //开启日志
		//创建邮件
		MimeMessage message = createMimeMessage(session,"发送人邮箱","收件人邮箱");
		//建立连接对象
		Transport transport = session.getTransport();
		//建立连接  qq,授权码
		transport.connect("发送人邮箱","这里填第三方授权码");
		//发送
		transport.sendMessage(message, message.getAllRecipients());
		//发送完毕后关闭连接
		transport.close();
	}
	
	
	/**
	 * @param session
	 * @param send 发送人
	 * @param recive  收件人
	 * @param cRecive	抄送人
	 * @param mRecive	密送人
	 * @return	邮件对象
	 * @throws Exception
	 */
	//,String cRecive,String mRecive 我这里不要抄送密送了
	public static MimeMessage createMimeMessage(Session session,String send,String recive) throws Exception{
		MimeMessage message = new MimeMessage(session);
		//添加发件人
		Address address = new InternetAddress(send,"发件人的name","UTF-8");
		message.setFrom(address);
		//设置邮箱标题,编码格式
		message.setSubject("这是java邮件的标题", "UTF-8");
		//设置正文
		message.setContent("正文内容", "text/html; charset=utf-8");
		//设置收件人类型: .TO普通收件人、CC抄送、BCC密送
		message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(recive,"收件人A","UTF-8"));
//		message.setRecipient(MimeMessage.RecipientType.CC, new InternetAddress(cRecive,"抄送人B","UTF-8"));
//		message.setRecipient(MimeMessage.RecipientType.BCC, new InternetAddress(mRecive,"密送人C","UTF-8"));
		
		//设置发件日期
		message.setSentDate(new Date());
		message.saveChanges();
		return message;
	}
	
}

获取三方邮箱登录授权码,以QQ邮箱为例:
在这里插入图片描述
在这里插入图片描述
程序运行结果:
在这里插入图片描述
在这里插入图片描述

发布了13 篇原创文章 · 获赞 15 · 访问量 2421

猜你喜欢

转载自blog.csdn.net/weixin_43274097/article/details/101756982