java中的邮件发送

java原生API邮件发送

在发送邮件前先确定自己邮箱类型,邮箱服务器地址,第三方管理是否开启,等等

package test.util;

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

public class SendEmail{
public static void sendEmail(String to,String content)throws MessagingExceptioon{
      //1创建连接对象
            Properties pro=new Properties();
      //2.设置协议
            pro.put("mail.transport.protocol","smtp");
      //3.设置发送邮件服务器
            pro.put("mail.smtp.host","smtp.office365.com");
      //4.进行授权
            pro.put("mail.smtp.auth","true");
      //5.邮件服务器具体端口及协议设定
            pro.setProperties("mail.smtp.port","587");
            pro.setProperties("mail.smtp.socketFactory.port","587");
            pro.setProperties("mail.smtp.starttls.enable","true");
      //6.认证信息
            Session s=Session.getInstance(pro,new Authenticator(){
               @Override
            protected PasswordAuthentication getPasswordAuthentication(){
                      return new PasswordAuthentication("你的邮箱","你的密码");
                      }
                 }
            );
      //7.创建邮件对象
            Message m=new MimeMessage(s);
      //8.设置邮件发送人
            m.setFrom(new InternetAddress("你的邮箱"));
      //9.设置接收人,to为接收者邮箱
            m.setRecipient(RecipientType.TO,new InternetAddress("to"));
      //10.设置主题
            m.setSubject("xxxx");
      //11.设置内容,content为内容
            m.setContent(content,"text/html;charset=utf-8");
      //12.发送
            Transport.send(m);
      }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值