SMTP发送邮件接口

卫深
2023-12-01

此文章为servlet写的

首先需要先下载一个jar包:mail jar


package sendemail;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailInfo {
    // 发送邮件的服务器的IP和端口    
    private String mailServerHost;  
    // 发送邮件的服务器的Smtp协议  
    private String mailServerPort="smtp.mxhichina.com";    
    // 邮件发送者的地址    
    private String fromAddress="";    
    // 邮件接收者的地址    
    private String toAddress;    
    // 登陆邮件发送服务器的用户名和密码    
    private String userName="";  
    private String password="";
    // 是否需要身份验证    
    private boolean validate = false;    
    // 邮件主题    
    private String subject;    
    // 邮件的文本内容    
    private String content;    
  
	public String getMailServerHost() {
		return mailServerHost;
	}

	public void setMailServerHost(String mailServerHost) {
		this.mailServerHost = mailServerHost;
	}

	public String getMailServerPort() {
		return mailServerPort;
	}

	public void setMailServerPort(String mailServerPort) {
		this.mailServerPort = mailServerPort;
	}

	public String getFromAddress() {
		return fromAddress;
	}

	public void setFromAddress(String fromAddress) {
		this.fromAddress = fromAddress;
	}

	public String getToAddress() {
		return toAddress;
	}

	public void setToAddress(String toAddress) {
		this.toAddress = toAddress;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public boolean isValidate() {
		return validate;
	}

	public void setValidate(boolean validate) {
		this.validate = validate;
	}

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public void senemail(){
		//发送邮件
		Properties props=new Properties();
		props.setProperty("mail.smtp.auth", "true");
		props.setProperty("mail.transport.protocol", "smtp");
		//设置邮箱smtp协议
		//"smtp.mxhichina.com"
		props.setProperty("mail.host", mailServerPort);
		//设置邮箱账号密码
		Session session1 =Session.getInstance(props,
				new Authenticator() {
			protected PasswordAuthentication getPasswordAuthentication() {
				//return new PasswordAuthentication("usadoctor@edoctordata.cn ","Edoctor1234");	
				return new PasswordAuthentication(userName,password);
			}
		});		
		session1.setDebug(true);		
		Message msg = new MimeMessage(session1);//创建message对象		
		try {
			//发件人
			msg.setFrom(new InternetAddress(fromAddress));
			//发件标题
			msg.setSubject(subject);
			//发件正文
			msg.setContent("<p><img src=\"http://edoctordata.vip:8080/img/logo.png\" /><div align=\"center\" style=\" border:#58CCE4 solid 1px;width:500px;align=\"center\" \"></p><font color=\"#0099cc\"><h2>邮件通知</h2><font size=\"2px;\"><div align=\"left\">"+content+"</div></font></br><div align=\"left\"><p>这是一封邮件</p></div></div>","text/html;charset=UTF-8");	  
			//指定收件人
			 msg.setRecipients(RecipientType.TO, 
			InternetAddress.parse(toAddress));
			Transport.send(msg);

/** 添加附件
			Multipart mainPart = new MimeMultipart();
			BodyPart body = new MimeBodyPart();
			body.setContent(content, "text/html;charset=UTF-8");
			BodyPart attachbody = new MimeBodyPart();
			//文件名
			System.out.println("fileName:"+fileName);
			FileDataSource fds = new FileDataSource(fileName);
			DataHandler dh = new DataHandler(fds);
			String fileNames = fileName.substring(fileName.lastIndexOf("\\"));
			System.out.println("fileNamess"+fileNames);
			BASE64Encoder enc = new BASE64Encoder(); 
			attachbody.setFileName("=?GBK?B?" + enc.encode(fileNames.getBytes("GBK")) + "?=");
			attachbody.setDataHandler(dh);
			mainPart.addBodyPart(body);
			mainPart.addBodyPart(attachbody);
			msg.setContent(mainPart);		
			//指定收件人			
			msg.setRecipients(RecipientType.TO, 
			InternetAddress.parse(toAddress));
			Transport.send(msg);
	*/
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
}
/**
有时会把一些参数放在xml配置文件中,下面是利用dom读取xml的一种方式
 Element element = null;
	  // 可以使用绝对路劲
	  File f = new File("edoctor-email.xml");
	  // documentBuilder为抽象不能直接实例化(将XML文件转换为DOM文件)
	  DocumentBuilder db = null;
	  DocumentBuilderFactory dbf = null;
	  try {
	   // 返回documentBuilderFactory对象
	   dbf = DocumentBuilderFactory.newInstance();
	   // 返回db对象用documentBuilderFatory对象获得返回documentBuildr对象
	   db = dbf.newDocumentBuilder();
	   // 得到一个DOM并返回给document对象
	   Document dt = db.parse(f);
	   // 得到一个elment根元素
	   element = dt.getDocumentElement();
	   // 获得根元素下的子节点
	   NodeList childNodes = element.getChildNodes();
	   // 遍历这些子节点
	   for (int i = 0; i < childNodes.getLength(); i++) {
	    // 获得每个对应位置i的结点
	    Node node1 = childNodes.item(i);
	    if ("email".equals(node1.getNodeName())) {
	     // 获得<emails>下的节点
	     NodeList nodeDetail = node1.getChildNodes();
	     // 遍历<emails>下的节点
	     for (int j = 0; j < nodeDetail.getLength(); j++) {
	      // 获得<emails>元素每一个节点
	      Node detail = nodeDetail.item(j);
	      if ("formAddress".equals(detail.getNodeName())){
	    	  fromAddress=detail.getTextContent();
	      } else if ("port".equals(detail.getNodeName())){
	    	  mailServerPort=detail.getTextContent();
	      }
	      else if ("userName".equals(detail.getNodeName())){
	    	  userName=detail.getTextContent();
	      }
	      else if ("userPwd".equals(detail.getNodeName())){
	    	  password=detail.getTextContent();
	      }
	     }
	    }
	   }
	  }
	  catch (Exception e) {
	   e.printStackTrace();
	  }*/

 

 

 类似资料: