首页 > 编程语言 > 详细

Java:发邮件

时间:2018-05-15 18:22:52      阅读:178      评论:0      收藏:0      [点我收藏+]
java 发邮件,有监控需要发送邮件到op通知很简单 直接调用

SendMail2.sendMail("zong_xuan@126.com","报警信息")


package com.stevezong.sendMail;

import java.io.IOException;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class SendMail2 {
	
	private static final String MAIL_HOST = "smtp.exmail.qq.com";
	private static final int MAIL_TIMEOUT = 3000;
	private static final boolean MAIL_AUTH = true;
	private static final String AUTH_USER_ADDRESS = "邮箱";
	private static final String AUTH_USER_PASSWORD = "邮箱密码";
	private static final String AUTH_USER_NICKNAME = "监控看门狗";

	//receiver 收件人
	//mailInfo 邮件信息
	public static void sendMail(String receiver, String mailInfo) throws IOException, MessagingException  {
		Properties serverProperties = new Properties();
		serverProperties.put("mail.smtp.host", MAIL_HOST);
		serverProperties.put("mail.smtp.auth", MAIL_AUTH);
		serverProperties.put("mail.smtp.timeout", MAIL_TIMEOUT);
		Authenticator authenticator = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication(AUTH_USER_ADDRESS, AUTH_USER_PASSWORD);
			}
		};
		Session session = Session.getInstance(serverProperties, authenticator);
		Message mailMsg = new MimeMessage(session);
		//邮件标题
		mailMsg.setSubject("XXX异常");
		mailMsg.setFrom(
				new InternetAddress(MimeUtility.encodeText(AUTH_USER_NICKNAME) + "<" + AUTH_USER_ADDRESS + ">"));
		mailMsg.setRecipient(RecipientType.TO, new InternetAddress(receiver));
		mailMsg.setRecipient(RecipientType.CC, new InternetAddress("抄送人邮箱"));
		Multipart mailContent = new MimeMultipart();
		BodyPart contentPart = new MimeBodyPart();
		contentPart.setText(mailInfo+"time:"+System.currentTimeMillis());
		mailContent.addBodyPart(contentPart);
		mailMsg.setContent(mailContent);
		Transport.send(mailMsg);
		System.out.println("sendMailSucceed!!!");
	}
}




Java:发邮件

原文:http://blog.51cto.com/lmdtx/2116616

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!