java发送邮件详解

1.导入jar包

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

2.代码案例

import org.jboss.cache.factories.annotations.Start;

import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;
import java.util.Random;

public class MailUtils {

	/**
	 * @param to 		收件人
	 * @param content   邮件的内容
	 * @param subject   邮件的主题
	 */
	public static boolean sendMail(String subject,String to,String content){
		//设置发送邮件的协议为smtp
		//props.put("mail.transport.protocol","SMTP");
		//发送邮件的服务器地址  本地 localhost
		Properties props =  new Properties();
		props.put("mail.smtp.host", "smtp.qq.com");//根据不同的邮箱服务器进行修改
		//设置安全认证为true
		props.put("mail.smtp.auth", "true");
		props.put("mail.username","xxxxxxxxxxx@qq.com" );
		props.put("mail.password", "xxxxxxxxxxx");
		
		//创建密码校验器
		Authenticator auth = new Authenticator() {
			@Override
			protected PasswordAuthentication getPasswordAuthentication() {
				// 设置连接邮件的用户名和密码
				return new PasswordAuthentication("xxxxxxxxxxx@qq.com", "xxxxxxxxxxx");//连接服务器的用户名和密码
			}
		};
		//创建邮件的会话对象
		Session session = Session.getInstance(props, auth);
		//创建邮件对象
		MimeMessage message = new MimeMessage(session);
		//设置邮件给谁发送   TO正常发送的邮件 
		try {
			//设置发送邮件的邮箱
			message.setFrom(new InternetAddress("xxxxxxxxxxx@qq.com"));
			//设置收件人
			message.addRecipient(RecipientType.TO, new InternetAddress(to));
			//设置邮件主题
			message.setSubject(subject);
			//设置邮件的内容
			message.setContent(content,"text/html;charset=UTF-8");
			//发送邮件
			Transport.send(message);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.err.println("邮件发送失败的原因是:"+e.getMessage());
			System.err.println("具体的错误原因");
			e.printStackTrace(System.err);
			return false;
		}
		return true;
	}

	public static final char[] chars={'1','2','3','4','5','6','7','8','9','0'};
	public static Random random=new Random();
	public static String getVerificationCode(){
		StringBuffer sb=new StringBuffer();
		for(int i=0;i<=5;i++){
			sb.append(chars[random.nextInt(chars.length)]);;
		}
		return sb.toString();
	}

    //测试
	public static void main(String[] args) {
		String s = getVerificationCode();
		sendMail("验证码","xxxxxxxxxxx@qq.com"," 您的验证码是: "+s);
		System.out.println("邮件发送完毕       "+s);
	}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值