×

JavaMail使用outlook邮箱发送邮件

我的笔记 我的笔记 发表于2018-12-11 10:44:27 浏览6195 评论0

抢沙发发表评论

问题:

    在一次客户要求更换邮件发送方式的时候。需要使用outlook邮箱,端口是587.所以需要对原有的发邮件代码做一些修改

解决办法:

我直接把工具类贴出来,我只在类中加了两行代码:

props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.port", "587");

工具类如下:

import java.io.File;
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.activation.CommandMap;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.activation.MailcapCommandMap;
import javax.mail.*;
import javax.mail.internet.*;
import com.datadriver.common.util.log.Logger;
import com.datadriver.sequoia.util.Switch;

/**
 * @author: john
 * @Email: chenjun_crazy@hotmail.com
 * @Company: DataDriver©2010/www.datadriver.com.cn
 * @Action:发送邮件工具包
 * @DATE: Sep 28, 2010
 */
public class SendMailUtil {

	private String host;
	private String mail;
	private String password;
	private String from;
	private List<String> to;
	private String title;
	private String content;
	private List<String> fileNames;
	private List<String> showNames;

	class SendEmailThread implements Runnable {

		@Override
		public void run() {
			try {
				Logger.debug("线程运行正在发送至" + to + "....");
				System.err.println("线程运行正在发送....");
				String result = sendEmail(host, mail, password, from, to,
						title, content, fileNames, showNames);
				System.err.println("发送结果:" + result);
				Logger.debug("发送结果:" + result);
				Thread.sleep(100);
			} catch (Exception e) {
				e.printStackTrace();
				Logger.error(e);
				Logger.debug(e);
				System.err.println("错误,线程停止....");
			}
		}
	}

	/**
	 * 发送邮件
	 * 
	 * @param host
	 * @param mail
	 * @param password
	 * @param from
	 * @param to
	 * @param title
	 * @param content
	 * @param fileNames
	 * @param showNames
	 * @return
	 */
	public String send(String host, String mail, String password, String from,
			List<String> to, String title, String content,
			List<String> fileNames, List<String> showNames) {
		String result = "邮件发送成功";
		if (fileNames == null || fileNames.size() == 0) {
			fileNames = new ArrayList<String>();
		}
		if (showNames == null || showNames.size() == 0) {
			showNames = new ArrayList<String>();
		}
		String path = SendMailUtil.class.getClassLoader().getResource("/")
				.getPath();
		path = path.replaceAll("%20", " ");
//		String logoFile = path + "com/datadriver/template/mail_logo.png";
//		fileNames.add(logoFile);
//		showNames.add("mail_logo.png");
		this.host = host;
		this.mail = mail;
		this.password = password;
		this.from = from;
		this.to = to;
		this.title = title;
		this.content = content;
		this.fileNames = fileNames;
		this.showNames = showNames;
		Thread threadE = null;
		try {
			// 启动线程
			System.err.println("启动线程....");
			Logger.debug("启动线程....");
			SendEmailThread sendEmailThread = new SendEmailThread();
			threadE = new Thread(sendEmailThread);
			threadE.start();
		} catch (Exception e) {
			e.printStackTrace();
			Logger.error(e);
			Logger.debug(e);
			threadE.stop();
			if (threadE != null) {
				threadE.interrupt();
			}
			Logger.error(Thread.currentThread().getName());
			System.err.println("错误,线程停止....");
			System.out.println(Thread.currentThread().getName() + "------");
		}
		return result;
	}
	
	
	/**
	 * 发送邮件
	 * 
	 * @param host
	 * @param mail
	 * @param password
	 * @param from
	 * @param to
	 * @param title
	 * @param content
	 * @param fileNames
	 * @param showNames
	 * @return
	 */
	public static String sendEmail(String host, String mail, String password,
			String from, List<String> to, String title, String content,
			List<String> fileNames, List<String> showNames) {
		//是否需要SSL加密  
	    boolean ssl = true;  
		String result = "邮件发送成功";
		// Get system properties
		Properties props = System.getProperties();
		
		// Setup mail server
		props.put("mail.smtp.host", host);
		props.put("mail.smtp.starttls.enable", "true");
		//通过ssl方式发送
		//props.put("mail.smtp.ssl.enable",ssl ? "true" : "false"); 
		 
		// Setup mail port
		props.put("mail.smtp.port", "587");
		props.put("mail.smtp.auth", "true"); // 通过验证
		
		// Get session
		
		MyAuthenticator myauth = new MyAuthenticator(mail, password);
		Session session = Session.getDefaultInstance(props, myauth);
		// session.setDebug(true);
		MimeMessage message = null;
		for (int i = 0; i < to.size(); i++) {
			// Set the to address
			// Define message
			Logger.debug("初始化设置发送邮件至:" + to.get(i));
			System.err.println("初始化设置发送邮件至:" + to.get(i));
			message = new MimeMessage(session);
			try {
				message.setText(content);
			} catch (MessagingException e1) {
				Logger.error(e1);
				Logger.debug(e1);
			}
			try {
				message.setFrom(new InternetAddress(from));
			} catch (AddressException e) {
				Logger.error(e);
				Logger.debug(e);
			} catch (MessagingException e) {
				Logger.error(e);
				Logger.debug(e);
			}

			// Set the subject
			try {
				message.setSubject(title);
			} catch (MessagingException e) {
				Logger.debug(e);
				Logger.error(e);
				result = "设置邮件主题错误";
			}
			// Set the content
			try {
				MailcapCommandMap mailcapCommandMap = (MailcapCommandMap) CommandMap
						.getDefaultCommandMap();
				mailcapCommandMap
						.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
				mailcapCommandMap
						.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
				mailcapCommandMap
						.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
				mailcapCommandMap
						.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
				mailcapCommandMap
						.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
				CommandMap.setDefaultCommandMap(mailcapCommandMap);

				BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
				// 给BodyPart对象设置内容和格式/编码方式
				mdp.setContent(content, "text/html;charset=utf-8");
				MimeMultipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对
				// 象(事实上可以存放多个)
				mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
				mm.setSubType("related");
				// 把mm作为消息对象的内容
				if (fileNames != null && fileNames.size() > 0) {
					MimeBodyPart filePart;
					FileDataSource filedatasource;
					// 逐个加入附件
					for (int j = 0; j < fileNames.size(); j++) {
						filePart = new MimeBodyPart();
						filedatasource = new FileDataSource(fileNames.get(j));
						filePart
								.setDataHandler(new DataHandler(filedatasource));
						
						try {
							filePart.setFileName(MimeUtility
									.encodeText(showNames.get(j)));
						} catch (UnsupportedEncodingException e) {
							Logger.error(e);
							Logger.debug(e);
						}
						filePart.setHeader("Content-ID", "filepart"+j);
						mm.addBodyPart(filePart);
					}
				}
				message.setContent(mm);
			} catch (MessagingException e) {
				Logger.debug(e);
				Logger.error(e);
				result = "设置邮件内容错误";
			}
			try {
				message.addRecipient(Message.RecipientType.TO,
						new InternetAddress(to.get(i)));
			} catch (AddressException e) {
				Logger.debug(e);
				Logger.error(e);
				result = "邮件地址解析失败";
			} catch (MessagingException e) {
				result = "邮件信息错误";
			}
			try {
				message.saveChanges();
			} catch (MessagingException e) {
				Logger.debug(e);
				Logger.error(e);
				result = "邮件发送失败";
			}
			try {
				Transport.send(message);
			} catch (MessagingException e) {
				Logger.debug(e);
				Logger.error(e);
				result = "邮件发送失败";
			}
		}
		return result;
	}

	/**
	 * 获得模板
	 */
	public static String getEmailTemplate(File templateFile, Map dataMap) {
		String mailContent = ""; // 发邮件要的内容
		try {
			String templateContent = " ";
			FileInputStream fileinputstream = new FileInputStream(templateFile); // 读取模板文件
			int lenght = fileinputstream.available();
			byte bytes[] = new byte[lenght];
			fileinputstream.read(bytes);
			fileinputstream.close();
			templateContent = new String(bytes, "utf-8");
			Set<Object> keySet = dataMap.keySet();
			for (Object key : keySet) {
				Object value = dataMap.get(key);
				templateContent = templateContent.replaceAll(key.toString(),
				        value != null ? value.toString() : "");
			}
			mailContent = templateContent; // 发送邮件为html模板格式

		} catch (Exception e) {
			Logger.error(e);
			Logger.debug(e);
		}
		return mailContent;

	}
}


我的笔记博客版权我的笔记博客版权