⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 mailsender.java

📁 这是本人曾经在公司里用的,内部开发框架,基于struts+hibernate今天分享给大家
💻 JAVA
字号:
/**
 * 
 */
package cn.bway.common;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.SendFailedException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.http.HttpServletRequest;

/**
 * @author Kson
 *
 */
public class MailSender extends Authenticator {

	private String username = null; //�ʼ������ʺ��û���

	private String userpasswd = null; //�ʼ������ʺ��û�����

	protected BodyPart messageBodyPart = null;

	protected Multipart multipart = new MimeMultipart("related");

	protected MimeMessage mailMessage = null;

	protected Session mailSession = null;

	protected Properties mailProperties = System.getProperties();

	protected InternetAddress mailFromAddress = null;

	protected InternetAddress mailToAddress = null;

	protected Authenticator authenticator = null;

	protected String mailSubject = "";

	protected Date mailSendDate = null;

	protected String mailContent = null;

	//public static final String MAIL_FILe_PATH="c:/aa/";
	public static String MAIL_FILe_PATH;

	public static String getMAIL_FILe_PATH() {
		return MAIL_FILe_PATH;
	}

	public static void setMAIL_FILe_PATH(String le_PATH) {
		MAIL_FILe_PATH = le_PATH;
	}

	/**
	 * ���캯��

	 * @param smtpHost
	 * @param username
	 * @param password
	 */
	public MailSender(String smtpHost, String username, String password) {
		this.username = username;
		this.userpasswd = password;
		mailProperties.put("mail.smtp.host", smtpHost);
		mailProperties.put("mail.smtp.auth", "true");
		mailSession = Session.getDefaultInstance(mailProperties, this);
		mailMessage = new MimeMessage(mailSession);
		messageBodyPart = new MimeBodyPart();
	}

	/**
	 * ���÷����ʼ�������
	 */
	public void setMailContent(String fileName, String param[],
			String repaleParam[]) throws MessagingException {
		try {
			String filePath = getMAIL_FILe_PATH() + fileName;
			System.out.println("������" + filePath);
			File file = new File(filePath);
			int i = 0;
			String record = null;
			StringBuffer tmpStrBuf = new StringBuffer();
			FileReader fr = new FileReader(file);
			BufferedReader br = new BufferedReader(fr);
			record = new String();
			while ((record = br.readLine()) != null) {
				tmpStrBuf.append(record + "\n");
			}
			br.close();
			fr.close();
			while (i < param.length) {
				String paraVal = param[i];
				String repaleVal = repaleParam[i];
				int tmpIdx = tmpStrBuf.indexOf(paraVal);
				if (tmpIdx != -1) {
					tmpStrBuf.replace(tmpIdx, tmpIdx + paraVal.length(),
							repaleVal);
				}
				i++;
			}
			mailContent = tmpStrBuf.toString();
			//	    messageBodyPart.setText(mailContent);
			messageBodyPart
					.setContent(mailContent, "text/html; charset=GB2312");
			multipart.addBodyPart(messageBodyPart);
			System.out.println("���ڷ��ʼ������Ժ�......");
		} catch (IOException e) {
			System.out.println("�������!");
		}
	}

	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(username, userpasswd);
	}

	/**
	 * ���÷����ʼ��ı��⣡

	 */
	public void setSubject(String mailSubject) throws MessagingException {
		this.mailSubject = mailSubject;
		mailMessage.setSubject(mailSubject);
	}

	//public abstract void setMailContent(String mailContent) throws MessagingException;

	/**
	 * ���÷����ʼ�������
	 */
	public void setSendDate(Date sendDate) throws MessagingException {
		this.mailSendDate = sendDate;
		mailMessage.setSentDate(sendDate);
	}

	public void setAttachments(String attachmentName) throws MessagingException {
		messageBodyPart = new MimeBodyPart();
		DataSource source = new FileDataSource(attachmentName);
		messageBodyPart.setDataHandler(new DataHandler(source));
		int index = attachmentName.lastIndexOf(File.separator);
		String attachmentRealName = attachmentName.substring(index + 1);
		messageBodyPart.setFileName(attachmentRealName);
		multipart.addBodyPart(messageBodyPart);
	}

	/**
	 * 
	 * ���÷���Դ��ַ?
	 */
	public void setMailFrom(String mailFrom) throws MessagingException {
		mailFromAddress = new InternetAddress(mailFrom);
		mailMessage.setFrom(mailFromAddress);
	}

	/**
	 * ���÷���Ŀ�ĵ�ַ?
	 * 
	 */
	public void setMailTo(String[] mailTo, String mailType) throws Exception {
		for (int i = 0; i < mailTo.length; i++) {
			mailToAddress = new InternetAddress(mailTo[i]);
			if (mailType.equalsIgnoreCase("to")) {
				mailMessage.addRecipient(Message.RecipientType.TO,
						mailToAddress);
			} else if (mailType.equalsIgnoreCase("cc")) {
				mailMessage.addRecipient(Message.RecipientType.CC,
						mailToAddress);
			} else if (mailType.equalsIgnoreCase("bcc")) {
				mailMessage.addRecipient(Message.RecipientType.BCC,
						mailToAddress);
			} else {
				throw new Exception("Unknown mailType" + mailType + "!");
			}
		}
	}

	/**
	 *�����ʼ��ķ���
	 **/
	public void sendMail() throws MessagingException, SendFailedException {
		if (mailToAddress == null)
			throw new MessagingException("�����������д�ռ��˵�ַ!");
		mailMessage.setContent(multipart);
		try {
			Transport.send(mailMessage);
		} catch (SendFailedException se) {
			se.printStackTrace();
			throw se;
		}
		System.out.println("��ϲ�㣬�ʼ��Ѿ��ɹ�����!");
	}

	public static void sendmailmessage(String sendmailAddr, String mailtitle,
			String pararepale[], String param[], String mailhost,
			String mailpassword, String mailuser, String filepath)
			throws Exception {

		String[] toAddress = { sendmailAddr.trim() };

		String mailHost = mailhost; //�����ʼ��ķ������ַ? mail.nps.cn:25,SMTP.163.com
		String mailUser = mailuser; //�����ʼ��ķ������ʺ�
		String mailPassword = mailpassword; //�����ʼ��ķ�������������
		MailSender sendmails = new MailSender(mailHost, mailUser, mailPassword);

		sendmails.setSubject(mailtitle);
		sendmails.setSendDate(new Date());
		sendmails.setMailContent(filepath, param, pararepale);
		sendmails.setMailFrom(mailUser);
		sendmails.setMailTo(toAddress, "to");
		sendmails.sendMail();
	}

	public static void mailmessage(String email, HttpServletRequest request)
			throws Exception {
		if (request != null) {
			setMAIL_FILe_PATH(request.getRealPath("/emailInfo/"));
		} else {
			setMAIL_FILe_PATH("D:/workspace/edu/edu/web/emailInfo");
		}
		
//		Emailmessage pvo = (Emailmessage) EmailmessageManagerFactory
//				.getEmailmessageManager().getEmailmessage("3");
//		String title = pvo.getEmailtitle();
//		String content = pvo.getEmailcontent();
//		String date = new Date().toLocaleString();
//		String mailhost = pvo.getMailhost();
//		String mailpassword = pvo.getMailpassword();
//		String mailuser = pvo.getMailuser();
//
//		String param[] = { "@content", "@date", };
//		String pararepale[] = { content, date };
//		String filepath = "/sendmessage.template";
//		sendmailmessage(email, title, pararepale, param, mailhost,
//				mailpassword, mailuser, filepath);
	}

	public static void sentpassword(String email, String password,
			HttpServletRequest request) throws Exception {
		if (request != null) {
			setMAIL_FILe_PATH(request.getRealPath("/emailInfo/"));
		} else {
			setMAIL_FILe_PATH("D:/workspace/edu/edu/web/emailInfo");
		}
//		Emailmessage pvo = (Emailmessage) EmailmessageManagerFactory
//				.getEmailmessageManager().getEmailmessage("3");
//		String title = pvo.getEmailtitle();
//		//		String content = pvo.getEmailcontent();
//		String date = new Date().toLocaleString();
//		String mailhost = pvo.getMailhost();
//		String mailpassword = pvo.getMailpassword();
//		String mailuser = pvo.getMailuser();
//
//		String param[] = { "@password", "@date", };
//		String pararepale[] = { password, date };
//		String filepath = "/sendpassword.template";
//		sendmailmessage(email, title, pararepale, param, mailhost,
//				mailpassword, mailuser, filepath);
	}

	public static void main(String[] args) throws Exception {
		String email = "bway@21cn.com";
		mailmessage(email, null);
		System.out.println("���ͳɹ�!");
	}

}

⌨️ 快捷键说明

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