sendmailutil.java

来自「网上商城代码」· Java 代码 · 共 85 行

JAVA
85
字号
package com.fendou.util.mail;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailUtil {

	private MimeMessage message;
	private Properties props;
	private Session session;
	private String name;
	private String password;
	
	public SendMailUtil(String host,String name,String password){
		this.name=name;
		this.password=password;
		this.props=System.getProperties();
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.auth", "true");
		FendouAuthenticator auth=new FendouAuthenticator(name,password);
		session=Session.getDefaultInstance(props, auth);
		message=new MimeMessage(session);
	}
	
	public void setForm(String form){
		try {
			message.setFrom(new InternetAddress(form));
		} catch (AddressException e) {			
			e.printStackTrace();
		} catch (MessagingException e) {			
			e.printStackTrace();
		}
	}
	
	public void setTo(String to){
		try {
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
		} catch (AddressException e) {			
			e.printStackTrace();
		} catch (MessagingException e) {			
			e.printStackTrace();
		}
	}
	
	public void setSubject(String subject){
		try {
			message.setSubject(subject);
		} catch (MessagingException e) {			
			e.printStackTrace();
		}
	}
	
	public void setText(String text){
		try {
			message.setText(text);
		} catch (MessagingException e) {			
			e.printStackTrace();
		}
	}
	
	public boolean send(){
		try {
			Transport port =session.getTransport("smtp");
			port.connect((String)props.getProperty("mail.smtp.host"), name, password);
			port.sendMessage(message,message.getRecipients(Message.RecipientType.TO));
			port.close();
			return true;
		} catch (NoSuchProviderException e) {			
			e.printStackTrace();
			return false;
		}catch (MessagingException e) {			
			e.printStackTrace();
			return false;
		}
	}
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?