欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java使用JavaMail发送邮件的方法

程序员文章站 2024-03-11 12:59:37
本文实例讲述了java使用javamail发送邮件的方法。分享给大家供大家参考,具体如下: 代码一、email_autherticator.java 服务器验证代码...

本文实例讲述了java使用javamail发送邮件的方法。分享给大家供大家参考,具体如下:

代码一、email_autherticator.java 服务器验证代码

import javax.mail.authenticator;
import javax.mail.passwordauthentication;
public class email_autherticator extends authenticator {
  string username = "你邮箱的用户名";
  string password = "你邮箱的密码";
  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.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_to = "254173774@qq.com";
  private string mail_from = "hackboyo@126.com";
  private string mail_subject = "this is the subject of this test mail";
  private string mail_body = "this is mail_body of this test mail";
  private string personalname = "我的邮件";
  public void sendmail() throws sendfailedexception{
 try {
   properties props = new properties();//获取系统环境
   authenticator auth = new email_autherticator();//进行邮件服务用户认证
   props.put("mail.smtp.host", host);
   props.put("mail.smtp.auth", "true");
   system.out.println(props);
   session session = session.getdefaultinstance(props,auth);
   //设置session,和邮件服务器进行通讯
   mimemessage message = new mimemessage(session);
   message.setcontent("hello","text/plain");//设置邮件格式
   message.setsubject(mail_subject);//设置邮件主题
   message.settext(mail_body);//设置邮件内容
   message.setheader(mail_head_name, mail_head_value);//设置邮件标题
   message.setsentdate(new date());//设置邮件发送时期
   address address = new internetaddress(mail_from,personalname);
   message.setfrom(address);//设置邮件发送者的地址
   address toaddress = new internetaddress(mail_to);//设置邮件接收者的地址
   message.addrecipient(message.recipienttype.to,toaddress);
   system.out.println(message);
   transport.send(message);
   system.out.println("send mail ok!");
 } catch (exception e) {
   e.printstacktrace();
 }
 //return flag;
  }
}

代码三、test.java 测试发送邮件的代码

public class test {
  public static void main(string[] args) {
 mail m = new mail();
 try {
   m.sendmail();
 } catch (exception e) {
 }
  }
}

希望本文所述对大家java程序设计有所帮助。