使用JAVA实现发送邮件

首先我们需要一个账号验证的类Email_Autherticator.java

import javax.mail.Authenticator; 
import javax.mail.PasswordAuthentication; 

public class Email_Autherticator extends Authenticator {
	String username = "mfknuipgf314@126.com"; 
	  
    String password = "mfknuipgf"; 
    public Email_Autherticator() { 
    	super(); 
    } 
    public Email_Autherticator(String user,String pwd){ 
    	super(); 
    	username = user; 
    	password = pwd; 
    } 
    public PasswordAuthentication getPasswordAuthentication(){ 
    	return new PasswordAuthentication(username,password); 
    } 
}

接着是一个邮件发送的类Mail.java

import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message;

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

public class Mail
{
  private String host = "smtp.126.com";

  private String mail_head_name = "this is head of this mail";

  private String mail_head_value = "this is head of this mail";

  private String mail_from = "mfknuipgf314@126.com";

  private String personalName = "我的邮件";

  public void sendMail(List<String> recipients, String mail_subject, String mail_body) throws SendFailedException {
    try { Properties props = new Properties();
      Authenticator auth = new Email_Autherticator();
      props.put("mail.smtp.host", this.host);
      props.put("mail.smtp.auth", "true");
      System.out.println(props);
      Session session = Session.getDefaultInstance(props, auth);

      MimeMessage message = new MimeMessage(session);
      message.setContent("Hello", "text/plain");
      message.setSubject(mail_subject);
      message.setText(mail_body);
      message.setHeader(this.mail_head_name, this.mail_head_value);
      message.setSentDate(new Date());
      Address address = new InternetAddress(this.mail_from, this.personalName);
      message.setFrom(address);

      int num = recipients.size();
      InternetAddress[] addresses = new InternetAddress[num];
      for (int i = 0; i < num; i++) {
        addresses[i] = new InternetAddress((String)recipients.get(i));
      }
      message.setRecipients(Message.RecipientType.TO, addresses);

      System.out.println(message);
      Transport.send(message);
      System.out.println("Send Mail Ok!");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

同时,还需要二个jar包,activation.jar和mail.jar

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值