Javamail发送邮件

最近在项目中集成发送邮件功能,发现由于邮箱服务商规则变化跟完善,有了不少的坑。

1、端口:一般默认是25,这样很多可以不定义端口,但是有些必须要定义,而且不一定是25

2、授权码:新浪默认是密码并且开始协议,163如果默认开启则可以用密码,但是设置了授权就必须使用授权码,并且手动开启协议;QQ默认是不开启的,需要设置了授权码才能开启。而且一个授权码如果多处使用可能会异常。

3、 SSL加密开启情况也不一致

4、邮箱登录名没有大小写除非,但是在发送校验的一般是处分大小写的,建议小写。

 

样例:

import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.sun.mail.util.MailSSLSocketFactory;
 
public class SendEmail {
	
	private Logger log = LogManager.getLogger(getClass());
	
	private String accout ;//发件人的账号
	private String password;//授权码
	private static String  stmp = "";//协议
	private static int  port = 25;//端口

	/**
	 * @param accout 发送人账号
	 * @param password 授权码
	 */
	public SendEmail(String accout, String password) {
		this.accout = accout;
		this.password = password;
		//根据发送人的账号选择相应的协议
		if (accout.contains("@163.com")) {
			stmp = "smtp.163.com";
			port = 994;
		}else if (accout.contains("@qq.com")) {
			stmp = "smtp.qq.com";
			port = 465;
		}else if (accout.contains("@sina.cn")) {
			stmp = "smtp.sina.cn";
			port = 25;
		}else if (accout.contains("@sina.com")) {
			stmp = "smtp.sina.com";
			port = 25;
		} else {
			stmp = "smtp."+accout.substring(accout.indexOf("@")+1);
		}
	}
	/**
	 * @param receiver 收件人
	 * @param title 邮件主题
	 * @param content 邮件正文 (可使用HTML标签)
	 * @throws Exception 
	 */
	public void sendEmail(String receiver,String title,String content){
		for(int i=0;i<3;i++) {//尝试3次,防止网速不好发不出去
			try {
				// 创建Properties 类用于记录邮箱的一些属性
				Properties props = new Properties();
				// 表示SMTP发送邮件,必须进行身份验证
				props.put("mail.smtp.auth", "true");
				//此处填写SMTP服务器
				props.put("mail.smtp.host", stmp);
				props.setProperty("mail.transport.protocol", "smtp");
				// 此处填写你的账号
				props.put("mail.user", accout);
				// 此处的密码就是前面说的16位STMP口令
				props.put("mail.password", password);
				//端口号
				if((accout.contains("@sina"))){
					props.put("mail.smtp.port", port);
				}
				
				if(!(accout.contains("@163"))){
					props.put("mail.smtp.starttls.enable", "true");
				}
				
				//开启 SSL 加密 (qq、新浪邮箱不需要 SSL 加密)
				if(!(accout.contains("@sina") || accout.contains("@qq"))){
					
					MailSSLSocketFactory sf = new MailSSLSocketFactory();
					sf.setTrustAllHosts(true);
					props.put("mail.smtp.ssl.enable", "true");
					props.put("mail.smtp.ssl.socketFactory", sf);
				}
 
				// 构建授权信息,用于进行SMTP进行身份验证
				Authenticator authenticator = new Authenticator() {
 
					protected PasswordAuthentication getPasswordAuthentication() {
						// 用户名、密码
						String userName = props.getProperty("mail.user");
						String password = props.getProperty("mail.password");
						return new PasswordAuthentication(userName, password);
					}
				};
				// 使用环境属性和授权信息,创建邮件会话
				Session mailSession = Session.getInstance(props, authenticator);

				mailSession.setDebug(true);
				// 创建邮件消息
				MimeMessage message = new MimeMessage(mailSession);
				// 设置发件人
				InternetAddress form = new InternetAddress(
						props.getProperty("mail.user"));
				message.setFrom(form);
				// 设置收件人的邮箱
				InternetAddress to = new InternetAddress(receiver);
				message.setRecipient(RecipientType.TO, to);
				// 设置邮件标题
				message.setSubject(title);

				// 新浪发送邮件必须要有主题哦,否则永远无法发送成功!
				message.setText("通知邮件");
				// 设置邮件的内容体
				message.setContent(content, "text/html;charset=UTF-8");
				// 设置时间
				message.setSentDate(new Date());
				
				message.addRecipients(MimeMessage.RecipientType.CC, InternetAddress.parse(props.getProperty("mail.user")));
				// 发送邮件
				Transport.send(message);
				System.out.println("发送成功");
				
				break;
			} catch (AddressException e) {
				log.debug("邮箱地址异常配置,发送通知邮件失败");
				e.printStackTrace();
			} catch (MessagingException e) {
				log.debug("发送通知邮件失败"+e);
				e.printStackTrace();
			} catch (GeneralSecurityException e) {
				log.debug("发送通知邮件失败"+e);
				e.printStackTrace();
			} catch (Exception e) {
				log.debug("发送通知邮件失败"+e);
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) throws Exception {
		SendEmail sendEmail = new SendEmail("###@sina.cn","***");
		sendEmail.sendEmail("to@163.com", "邮件标题","邮件正文----");
	}
	


}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值