使用Java代码发送邮件

看这个之前,首先确定你拥有了发送邮件的账号以及授权码,(PS:授权码不是密码,是开通pop3服务,可自行百度)

直接上代码,必要信息有所隐藏,所以请勿照搬,请多看注释!!!多看注释!!!多看注释!!!

所使用的jar——pom.xml中引用,若不是可以 点击下载——> 程序中使用的jar mail.jar 【完全免费】

    <dependency>
      <groupId>com.sun.mail</groupId>
      <artifactId>javax.mail</artifactId>
      <version>1.6.2</version>
    </dependency>


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;


/**
 * description:容易导错包,需要注意
 * @author 狼芒
 * String receiver:收件人邮箱账号
 * String activationCode:发送的激活码(或者内容)
 */


public class SentEmail {
	public String sentEmail(String receiver,String activationCode) {
		String result = "success sent to: "+receiver+"\tabout:\t"+activationCode;
		//  得到session 
		Properties props = new Properties();
//		props.setProperty("mail.host", "smtp.163.com");
		props.setProperty("mail.host", "smtp.qq.com");
		props.setProperty("mail.smtp.auth", "true");

		props.setProperty("mail.smtp.auth", "true");//开启认证
		props.setProperty("mail.debug", "true");//启用调试
		props.setProperty("mail.smtp.timeout", "1000");//设置链接超时
		props.setProperty("mail.smtp.port", "465");//设置端口
		props.setProperty("mail.smtp.socketFactory.port", "465");//设置ssl端口
		props.setProperty("mail.smtp.socketFactory.fallback", "false");
		props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

		Authenticator auth = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
//				设置账号以及授权码
 				return new PasswordAuthentication("***账号***", "****授权码***");
			}
		};
		
		Session session = Session.getInstance(props, auth);
		
		/*
		 * 2、创建MimeMessage
		 */
		MimeMessage msg = new MimeMessage(session);
		try {
//			设置发件人
			msg.setFrom(new InternetAddress("***发送人账号**@qq.com","**可以给自己起个别名**"));
//			设置收件人
			msg.setRecipients(RecipientType.TO, receiver);
//			设置抄送---允许围观
//			msg.setRecipients(RecipientType.CC, "*********@qq.com");
//			设置暗送---在别人不知道的情况下发送到这里
//			msg.setRecipients(RecipientType.BCC, "***********@qq.com");
//			设置标题
			msg.setSubject("设置副标题");
//			设置内容
			msg.setContent(activationCode,"text/html;charset=utf-8");
			//发送邮件
			Transport.send(msg);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			result = e.getMessage();
			e.printStackTrace();
		}
		return result;
	}
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值