java发送邮件

首先引入jar包:

    <dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>

 

代码:需要注意的是transport.connect()中的不是密码,而是授权码,163为例,去网页登录获取授权码,然后需要在设置里开启SMTP服务

package mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailAsynchronization extends Thread{
 	String subject;
	String Text;
	String Address;
	public MailAsynchronization(String subject,String Text,String Address) {
		this.subject=subject;
		this.Text=Text;
		this.Address=Address;
	}
	public  void SendMail() throws Exception {
	    Properties props = new Properties();
	       // 发送服务器需要身份验证
	       props.setProperty("mail.smtp.auth", "true");
	       // 设置邮件服务器主机名
	       props.setProperty("mail.host", "smtp.163.com");
	       // 发送邮件协议名称
	       props.setProperty("mail.transport.protocol", "smtp");
	       //设置邮箱端口
	       props.setProperty("mail.smtp.port", "25");
	       Session session = Session.getInstance(props);
	       Message msg = new MimeMessage(session);
	       msg.setSubject(subject);
	       msg.setContent(Text, "text/html;charset=utf-8");
	       msg.setFrom(new InternetAddress("guanmaolin00@163.com"));
	       String[] toAddress = this.Address.split(";");
           for(int i=0;i< toAddress.length ;i++){
               msg.addRecipient(Message.RecipientType.TO, new 
          InternetAddress(toAddress[i]));
           }
	       Transport transport = session.getTransport();
	       transport.connect("guanmaolin00@163.com", "YIUKWGGILTKYEJPH");
	       
	       transport.sendMessage(msg, msg.getAllRecipients());
	       transport.close();
 	 }
	@Override
	public void run() {
		try {
			this.SendMail();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public static void main(String[] args) {
		MailAsynchronization ma =new MailAsynchronization("测试啊啊啊","哈哈哈哈","1004514670@qq.com");
		ma.start();
	}
}

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页