JavaMail工具类的创建

先创建一个名为MailUtils工具类:

public class MailUtils {
    public static void sendMail(String email, String emailMsg)throws AddressException, MessagingException {  
        Properties props = new Properties();  

        // 发送服务器需要身份验证  
        props.setProperty("mail.smtp.auth", "true");  
        // 设置邮件服务器主机名  
        props.setProperty("mail.host", "smtp.126.com");  
        // 发送邮件协议名称  
        props.setProperty("mail.transport.protocol", "smtp");  

        // 设置环境信息  
        Session session = Session.getInstance(props);  

        // 创建邮件对象  
        Message msg = new MimeMessage(session); 
        //设置主题 
        msg.setSubject("测试");  
        // 设置邮件内容  
        msg.setContent(emailMsg, "text/html;charset=utf-8");
        // 设置发件人  
        msg.setFrom(new InternetAddress("linlilove@126.com"));  

        Transport transport = session.getTransport();  
        // 连接邮件服务器  
        transport.connect("linlilove", "授权码");  
        // 发送邮件  
        transport.sendMessage(msg, new Address[] {new InternetAddress(email)});  
        // 关闭连接  
        transport.close(); 
    }   
}

然后新建一个测试类来调用这个类的sendMail方法:

public class Test {
    public static void main(String[] args) throws AddressException, MessagingException {
        //设置要发送的目标邮箱
        String email = "answerlin@163.com";
        //设置邮件内容
        String emailMsg = "test";
        //调用方法发送邮件
        MailUtils.sendMail(email, emailMsg);
    }
}

PS:工具类里的授权码,要登录邮箱打开POP3/IMAP/SMTP服务,然后设置授权码。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值