Java:发邮件

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java:发邮件相关的知识,希望对你有一定的参考价值。

java 发邮件,有监控需要发送邮件到op通知很简单 直接调用

SendMail2.sendMail("[email protected]","报警信息")


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:发邮件的主要内容,如果未能解决你的问题,请参考以下文章

java windows自动化-mail自动发邮件

如何在Java ee项目中如何调用outlook发邮件

Java发邮件简单实现

关于java mail 发邮件的问题总结(转)

Java实现发邮件功能

如何用java发邮件?[重复]