ITeye博客

javaMail操作

CodeToMyLaw · 2012-05-21 20:17 · Web前端 · Markdown

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;

import cn.hs.dpl.pojo.AppInfo; import cn.hs.dpl.pojo.AppModDesc; import cn.hs.dpl.pojo.UserInfo;

public class SendMailUtils {

/**
 * 
 * @param from
 *            发件人的地址
 * @param to
 *            收件人地址
 * @param titleMsg
 *            邮件标题
 */
public void sendMail(String from, String to, String title, String host) {
	
	try {
		//系统所在的URL
		String url = SystemPropertiesUtils.getSystemParamValue("sysUrl");

		Properties props = new Properties();
		props.put("mail.smtp.host", host);// 指定SMTP服务器
		props.put("mail.smtp.auth", "false");// 指定是否需要SMTP验证,为false时,不用指定用户名、密码
		Session mailSession = Session.getDefaultInstance(props);

		mailSession.setDebug(true);// 是否在控制台显示debug信息

		MimeMessage message = new MimeMessage(mailSession);
		message.setFrom(new InternetAddress(from));// 发件人
		message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));// 收件人
		// 将中文转化为GB2312编码
		message.setSubject(title, "GB2312"); // 邮件主题
		message.setContent("<a href='"+ url +"'>请点击此链接进行评审</a>",
				"text/html;charset=utf-8");// 邮件内容
		message.saveChanges();

		Transport transport = mailSession.getTransport("smtp");
		transport.connect(host, null, null);
		transport.sendMessage(message, message.getAllRecipients());
		transport.close();
	} catch (Exception e) {
		LoggerUtil2file.tranceERROR("邮件发送失败,请检查邮件的配置是否正确!", e);
	}
}

/**
 * @param mailTo 要发送的邮件地址
 * @param appInfo 要评审的应用信息
 * 
 */
public static void sendMailToUser(UserInfo userInfo, AppModDesc appModDesc) throws Exception {

// 判断系统配置中是否启用发送邮件 String useMail = SystemPropertiesUtils.getSystemParamValue("useMail"); if("no".equalsIgnoreCase(useMail)) { return; }

	String mailTo = userInfo.getUserNotes();

// 从系统配置中得到邮箱服务器地址 String host = SystemPropertiesUtils.getSystemParamValue("mailHost"); String modType= appModDesc.getChangeType().equalsIgnoreCase(Const.MODIFYITEM_ADD)? "添加":appModDesc.getChangeType().equalsIgnoreCase(Const.MODIFYITEM_DEL)?"删除":"修改" ; String title = ""; if(Const.REVIEW_COMMIT.equalsIgnoreCase(appModDesc.getReviewPass())) { title = ",入库,请评审!"; } else { title =",被驳回,请重新提交!"; } // 从系统配置得到发送者 String mailFrom = SystemPropertiesUtils.getSystemParamValue("mailFrom"); // 从系统配置得到发送目标邮件的后缀 String mailSuffix = SystemPropertiesUtils.getSystemParamValue("mailSuffix"); SendMailUtils sm = new SendMailUtils();

	sm.sendMail(mailFrom, mailTo + mailSuffix, title, host);
}

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。