Mail工具类

1.mail

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType; 
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import javax.mail.internet.MimeBodyPart;

public class Mail {
	private String from; // 发件人地址
	private String password; // 发件人密码
	// 收件人,以及收件人接收方式的映射
	private Map<String, RecipientType> recipientsMap = new HashMap<String, RecipientType>();
	private String subject; // 邮件主题
	private List<File> attachments = new ArrayList<File>(); // 附件列表
	private String body; // 邮件正文
	private RecipientType type = RecipientType.TO; // 默认的邮件接收类型

	public Mail() {
	}

	/**
	 * Construct a Mail using the specified email address and password.
	 * 
	 * @param from
	 *            the sender's address eg. hello@163.com
	 * @param password
	 *            the password.
	 */
	public Mail(String from, String password) {
		this.from = from;
		this.password = password;
	}

	/**
	 * Construct a Mail.
	 * 
	 * @param from
	 *            the sender's address eg. hello@163.com
	 * @param password
	 *            the password.
	 * @param recipients
	 *            an array of recipients.
	 * @param type
	 *            the {@link RecipientType}
	 * @param subject
	 *            the subject.
	 * @param body
	 *            the body.
	 * @param attachments
	 *            a list of attachments.
	 */
	public Mail(String from, String password, String[] recipients, RecipientType type, String subject, String body,
			File... attachments) {
		this(from, password);

		// 添加接收者,及其接收方式
		for (String recipient : recipients) {
			if (!this.recipientsMap.containsKey(recipient)) {
				this.recipientsMap.put(recipient, type);
			}
		}

		this.subject = subject;
		this.body = body;

		for (File file : attachments) {
			this.attachments.add(file);
		}
	}
	
	public Mail(String from, String password, String[] recipients, RecipientType type, String subject, String body,List<File> files) {
		this(from, password);

		// 添加接收者,及其接收方式
		for (String recipient : recipients) {
			if (!this.recipientsMap.containsKey(recipient)) {
				this.recipientsMap.put(recipient, type);
			}
		}

		this.subject = subject;
		this.body = body;

		for (File file : files) {
			this.attachments.add(file);
		}
	}
	

	/**
	 * Send the email.
	 * 
	 * @throws IOException
	 * @throws MessagingException
	 */
	public void send() throws MessagingException, IOException {
		File[] files = new File[attachments.size()];
		this.attachments.toArray(files);
		send(from, password, recipientsMap, subject, body, files);
	}

	/**
	 * Send the email to specified recipients and recipient type, such as TO,
	 * CC, BCC.
	 * 
	 * @param recipients
	 *            the recipients
	 * @param type
	 *            the type
	 * @throws MessagingException
	 * @throws IOException
	 */
	public void sendTo(String[] recipients, RecipientType type) throws MessagingException, IOException {
		Map<String, RecipientType> recipientsMap = new HashMap<String, RecipientType>();
		// 添加接收者,及其接收方式
		for (String recipient : recipients) {
			if (!this.recipientsMap.containsKey(recipient)) {
				recipientsMap.put(recipient, type);
			}
		}

		File[] files = new File[attachments.size()];
		this.attachments.toArray(files);
		send(this.from, this.password, this.recipientsMap, this.subject, this.body, files);
	}

	/**
	 * Send an email.
	 * 
	 * @param from
	 *            the sedner' s email address.
	 * @param password
	 *            the password.
	 * @param recipientsMap
	 *            a map of the recipients and type.
	 * @param subject
	 *            the subject of the email.
	 * @param body
	 *            the body of the email.
	 * @param attachments
	 *            one or more attachments can be attached to the email.
	 * @throws MessagingException
	 * @throws IOException
	 */
	public void send(String from, String password, Map<String, RecipientType> recipientsMap, String subject,
			String body, File... attachments) throws MessagingException, IOException {
		if (from == null || password == null)
			throw new MessagingException("From address and password can not be null.");

		Session session = getSession(from, password);
		MimeMessage msg = new MimeMessage(session);
		MimeMultipart contentList = new MimeMultipart(); // 邮件内容,包括正文和附件
		MimeBodyPart bodyPart = new MimeBodyPart(); // 邮件正文
		contentList.addBodyPart(bodyPart);
		msg.setContent(contentList);

		// 设置此次发送的发件人
		InternetAddress fromAddr = new InternetAddress(from);
		msg.setFrom(fromAddr); // 设置发件人

		if (recipientsMap == null || recipientsMap.keySet().size() <= 0)
			throw new MessagingException("Provide at least one recipient");

		if (body == null)
			body = "";

		if (subject == null)
			subject = "";

		// 设置邮件接收者
		setRecipients(msg, recipientsMap);

		// 设置邮件主题
		msg.setSubject(subject);

		// 设置邮件正文
		bodyPart.setContent(body, "text/html;charset=utf-8");

		// 添加附件
		if (attachments != null) {
			for (File file : attachments) {
				addAttachment(contentList, file);
			}
		}

		// 发送
		Transport.send(msg);
		System.out.println(recipientsMap.toString()+"邮件发送成功!");
	}

	/**
	 * Set the sender' s email address.
	 * 
	 * @param from
	 *            the address. eg. hello@163.com
	 * @param password
	 *            the password.
	 */
	public void setFrom(String from, String password) {
		this.from = from;
		this.password = password;
	}

	/**
	 * 为msg设置接收人
	 * 
	 * @throws MessagingException
	 */
	private void setRecipients(MimeMessage msg, Map<String, RecipientType> recipientsMap) throws MessagingException {
		RecipientType type = null;
		for (String recipient : recipientsMap.keySet()) {
			type = recipientsMap.get(recipient);
			msg.addRecipients(type, recipient);
		}
	}

	/**
	 * Add a recipient.
	 * 
	 * @param address
	 *            the recipient' s email address.
	 * @param type
	 *            the RecipientType
	 * @throws MessagingException
	 */
	public void addRecipient(String address, RecipientType type) {
		if (!this.recipientsMap.containsKey(address)) {
			this.recipientsMap.put(address, type);
		}
	}

	/**
	 * Add a recipient using the default RecipientType<br/>
	 * 
	 * @param address
	 *            the recipient' s email address.
	 * @throws MessagingException
	 */
	public void addRecipient(String address) {
		if (!this.recipientsMap.containsKey(address)) {
			this.recipientsMap.put(address, this.type);
		}
	}

	/**
	 * Get the Session using specified email address and password.
	 * 
	 * @param from
	 *            the sender' s email address
	 * @param password
	 *            the password
	 * @return the Session.
	 */
	private Session getSession(final String from, final String password) {
		Properties props = new Properties();
		final int index = from.indexOf("@");
		String host = from.substring(index + 1);
		props.setProperty("mail.host", "smtp." + host); // 设置邮件服务器
		props.setProperty("mail.smtp.auth", "true"); // 需要验证身份

		Authenticator auth = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(from.substring(0, index), password);
			}
		};

		return Session.getInstance(props, auth);
	}

	/**
	 * Set the body of the email.
	 * 
	 * @param body
	 *            the mail body.
	 */
	public void setMailBody(String body) {
		this.body = body;
	}

	/**
	 * Set the subject of the mail.
	 * 
	 * @param subject
	 *            the subject.
	 */
	public void setSubject(String subject) {
		this.subject = subject;
	}

	/**
	 * add attachments.
	 * 
	 * @param contentList
	 * @param file
	 * @throws IOException
	 * @throws MessagingException
	 */
	private void addAttachment(MimeMultipart contentList, File file) throws IOException, MessagingException {
		MimeBodyPart attachment = new MimeBodyPart();
		attachment.attachFile(file);
		attachment.setFileName(MimeUtility.encodeText(file.getName())); // 设置显示的文件名

		contentList.addBodyPart(attachment);
	}

	/**
	 * Add a attachment.
	 * 
	 * @param file
	 *            the file to be attached.
	 * @throws IOException
	 * @throws MessagingException
	 */
	public void addAttachment(File file) throws IOException, MessagingException {
		this.attachments.add(file);
	}

	public static void main(String[] args) throws MessagingException, IOException {
		String from = "***********@163.com";
		String password = "*******";

		String[] to = { "receiver1@163.com" };

		String subject = "Test MailUtils";
		String body = "";
		File file1 = new File("c:/yufuPay.crt");

		Mail mail = new Mail(from, password, to, RecipientType.TO, subject, body);
		mail.setMailBody("你好,我是正文"); // 设置正文
		mail.addRecipient("*******@163.com", RecipientType.CC);// 抄送
		mail.addRecipient("*******@qq.com", RecipientType.BCC);// 密送
		mail.addAttachment(file1); // 添加附件

		mail.send();
		System.out.println("邮件发送成功。");
	}
}

2.调用

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

import javax.mail.MessagingException;
import javax.mail.Message.RecipientType;

import org.apache.commons.lang3.StringUtils;

import sun.net.ftp.FtpClient;
import sun.net.ftp.FtpDirEntry;
import sun.net.ftp.FtpProtocolException;
import sun.net.ftp.FtpDirEntry.Type;

public class SendMailToMrchTranPdf {
	private static PropertiesManager pm = new PropertiesManager();
	private static String FTP_IP= pm.getString("FTP_IP","192.168.10.75");	
	private static String FTP_PORT= pm.getString("FTP_PORT","21");
	private static String FTP_USER_NAME= pm.getString("FTP_USER_NAME","ftpweb");
	private static String FTP_PASSWORD= pm.getString("FTP_PASSWORD","ftpweb");
	private static String FTP_PDF_ROUTE= pm.getString("FTP_PDF_ROUTE","/home/ftpweb/fssystem_pdf/");
	private static String LOCAL_PDF_ROUTE= pm.getString("LOCAL_PDF_ROUTE","D://");
	private static String FS_MAIL_USERNAME= pm.getString("FS_MAIL_USERNAME","*****@163.com");
	private static String FS_MAIL_PASSWORD= pm.getString("FS_MAIL_PASSWORD","*******");
	private static String FS_MAIL_SUBJECT= pm.getString("FS_MAIL_SUBJECT","交易流水");
	private static String FS_MAIL_BODY= pm.getString("FS_MAIL_BODY","交详情请查件附件!谢谢。");
	
	/**
	 * 发送ftp服务器中某天的pdf文件给商户邮箱中
	 * @param sendDay yyyyMMdd格式的日期
	 */
	public void sendMail(String sendDay){
        System.out.println("====================给商户发送交易流水开始"+DateUtil.getDate("yyyy-MM-dd HH:mm:ss")+"=====================");
		try {
			FtpClient ftp = FTPUtils.connectFTP(FTP_IP, Integer.valueOf(FTP_PORT), FTP_USER_NAME, FTP_PASSWORD);
			String day=DateUtil.getDate("yyyyMMdd");
			if(StringUtils.isNoneEmpty(sendDay)&&sendDay.length()==8&&this.checkYyyyMMdd(sendDay)){
				day=sendDay;
			}
			String todayPdfFileRoute=FTP_PDF_ROUTE+day+"/";
			Iterator<FtpDirEntry> ftpFiles=ftp.listFiles(todayPdfFileRoute);
			String receiveMail="";
			String pdfRoute="";
			//本地创建当天目录
			FTPUtils.createDir(LOCAL_PDF_ROUTE+day);
	        System.out.println("**************************日期参数:"+day+"*****************************");
			while (ftpFiles.hasNext()) {  //跳转到当天目录,读取商户目录
				FtpDirEntry fe=ftpFiles.next();
				List<File> pdfFiles=new ArrayList<File>();
				String name=fe.getName();
				if(name.contains("#")){
					receiveMail=name.split("#")[1];
					FS_MAIL_BODY=FS_MAIL_BODY.replaceAll("#", name.split("#")[2]);
					System.out.println("发送到邮箱:"+receiveMail+" 周期:"+name.split("#")[2]);
				}
				System.out.println("当天目录名称:"+name+"   type:"+fe.getType());
				if(Type.DIR.equals(fe.getType())){//进入pdf文件夹目录,读取pdf
					Iterator<FtpDirEntry> mrchPdf=ftp.listFiles(todayPdfFileRoute+name);
					//本地创建当天商户目录
					FTPUtils.createDir(LOCAL_PDF_ROUTE+day+"/"+name);
					while (mrchPdf.hasNext()) {
						FtpDirEntry pdf=mrchPdf.next();
						if(Type.FILE.equals(pdf.getType())){
							System.out.println("pdf文件夹目录:"+todayPdfFileRoute+name+"/"+pdf.getName()+"   type:"+pdf.getType());
							pdfRoute=todayPdfFileRoute+name+"/"+pdf.getName();
							//下载ftp服务器pdf文件到本地
							FTPUtils.download(LOCAL_PDF_ROUTE+day+"/"+name+"/"+pdf.getName(), pdfRoute,ftp);
							pdfFiles.add(new File(LOCAL_PDF_ROUTE+day+"/"+name+"/"+pdf.getName()));
						}
					}
				}
				//给商户发送邮件
				if(pdfFiles!=null&&pdfFiles.size()>0&&FTPUtils.emailFormat(receiveMail)){
					String[] receive = {receiveMail}; 	//接收方邮箱
					Mail mail = new Mail(FS_MAIL_USERNAME,FS_MAIL_PASSWORD,receive,RecipientType.TO, FS_MAIL_SUBJECT+"("+DateUtil.getDate("yyyy-MM-dd HH:mm:ss")+")", FS_MAIL_BODY,pdfFiles);
					mail.send();
				}
		        System.out.println("*******************************************************");
			}
			ftp.close();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (FtpProtocolException e) {
			e.printStackTrace(); 
		 } catch (MessagingException e) {
			e.printStackTrace();
		}
        System.out.println("====================给商户发送交易流水结束"+DateUtil.getDate("yyyy-MM-dd HH:mm:ss")+"=====================");
    }
	
	/**
	 * yyyyMMdd时间格式校验
	 * @param date
	 * @return
	 */
	public boolean checkYyyyMMdd(String date){
		 String a2 = "[0-9]{4}[0-9]{2}[0-9]{2}";//yyyyMMdd
		 if(Pattern.compile(a2).matcher(date).matches()){
			 return true;
		 }else{
			 return false;
		 }
	}
	
	public static void main(String[] args) {
		SendMailToMrchTranPdf sd=new SendMailToMrchTranPdf();
		sd.sendMail("20180226");
	}

}

3.获取跑property属性

/**
 * 
 * <p>
 * Title:国际化
 * </p>
 * <p>
 * Description:国际化相关类
 * </p>
 * <p>
 * Copyright: Beijing Watchdata Copyright (c)2010
 * </p>
 * <p>
 * Company: Beijing Watchdata CO,.Ltd
 * </p>
 * 
 * @author wu.yao
 * @version 1.0
 */
public class PropertiesManager {

	String baseName = "resource.resource";
	// private static String sysPath = System.getProperty("user.dir");
	// public String propertiesPath =sysPath+ "\\Icon\\message.properties";
	public java.util.ResourceBundle res;

	public PropertiesManager() {
		try {

			res = java.util.ResourceBundle.getBundle(baseName,
					java.util.Locale.getDefault());
			// res = ResourceBundle.getBundle( baseName, new
			// Locale("zh","CN","WINDOWS") );
			// res = ResourceBundle.getBundle( baseName, Locale.ENGLISH );
		} catch (java.util.MissingResourceException exp) {
			exp.printStackTrace();
		}
	}

	public String getString(String key) {
		return res.getString(key);
	}

	public String getString(String key, String defValue) {
		try {
			return res.getString(key);
		} catch (java.util.MissingResourceException exp) {
			exp.printStackTrace();
			return defValue;
		}
	}

	public static String encodeString(String input) {
		try {
			// System.out.println(input);
			input = new String(input.getBytes("GBK"), "UTF-8");
			// System.out.println(input);
		} catch (Exception e) {
			e.printStackTrace();
			e.printStackTrace();
		}
		return input;
	}

	/**
	 * Create the composite
	 * 
	 * @return int i 0=zh_Cn ,1=en
	 */
	public int getLocal() {
		int i = 0;
		if (java.util.Locale.getDefault().toString().equalsIgnoreCase("zh_CN"))
			i = 0;
		else if (java.util.Locale.getDefault().toString()
				.equalsIgnoreCase("en"))
			i = 1;
		return i;
	}

	public static void main(String args[]) {
		System.out.println(java.util.Locale.getAvailableLocales());
		System.out.println(java.util.Locale.getDefault());
		System.out.println(java.util.Locale.getISOCountries());
		System.out.println(java.util.Locale.getISOLanguages());
	}
}

4.属性配置

#ftp服务器相关参数
FTP_IP=192.168.10.75
FTP_PORT=21
FTP_USER_NAME=ftpweb
FTP_PASSWORD=ftpweb
#ftp服务器存放pdf文件目录(日期上一层目录)
FTP_PDF_ROUTE=/home/****/****/
#应用服务器存放pdf文件目录(日期上一层目录)
LOCAL_PDF_ROUTE=E://
#LOCAL_PDF_ROUTE=/home/****/****/
#财务发送邮件邮箱信息
#FS_MAIL_USERNAME=****@163.com
#FS_MAIL_PASSWORD=*********
FS_MAIL_USERNAME=*******
FS_MAIL_PASSWORD=*********
FS_MAIL_SUBJECT=****
FS_MAIL_BODY=您好,<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;附件中是#交易明细,请查收。<br>如有疑问请与****:88888888。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值