javamail 发送邮件实例

本文介绍了一种使用Java实现的邮件发送服务,该服务通过SMTP协议进行邮件的发送,并提供了详细的代码实现。文章还提到了如何配置邮件发送所需的属性,如开启debug模式、设置邮件服务器等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    public Boolean sendMail(String mailAddr, String mailTitle, String mailBody) throws MailSendException {
        MailUser mailUser = mailUserDao.queryPresent();
        if(mailUser == null)
        {
            throw new MailSendException(ErrorCode.MAIL_USER_NOT_EXISTS);
        }
        Properties property = new Properties();
        // 开启debug调试  
        property.setProperty("mail.debug", "true");
        // 发送服务器需要身份验证  
        property.setProperty("mail.smtp.auth", "true");
        // 设置邮件服务器主机名  
        property.setProperty("mail.host",mailUser.getMailHost());
        // 发送邮件协议名称  
        property.setProperty("mail.transport.protocol", "smtp");

        Session session = Session.getInstance(property);

        MimeMessage msg = new MimeMessage(session);
        try {
            msg.setFrom(new InternetAddress(mailUser.getMailUser()));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(mailAddr));
            msg.setSubject(mailTitle);
            msg.setText(mailBody);
        } catch (MessagingException ex) {
            Logger.getLogger(MailServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            throw new MailSendException(ErrorCode.MAIL_SEND_FAILED);
        }

        Transport transport = null;
        //todo : 为什么每个操作都提示要加try catch
        try {
            transport = session.getTransport();
        } catch (NoSuchProviderException ex) {
            Logger.getLogger(MailServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            throw new MailSendException(ErrorCode.MAIL_SEND_FAILED);
        }
        //截取邮箱账号
        String user = mailUser.getMailUser().substring(0,mailUser.getMailUser().indexOf("@"));
        try {
            transport.connect(user, mailUser.getMailPsw());
        } catch (MessagingException ex) {
            Logger.getLogger(MailServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            throw new MailSendException(ErrorCode.MAIL_SEND_FAILED);
        }

        try {
            transport.sendMessage(msg, msg.getRecipients(Message.RecipientType.TO));
            transport.close();
        } catch (MessagingException ex) {
            Logger.getLogger(MailServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
            throw new MailSendException(ErrorCode.MAIL_SEND_FAILED);
        }

        return true;
    }

注意:

1、如果需要SSL协议发送邮件,需要把

property.setProperty("mail.transport.protocol", "smtp");
里面的smtp换成smtps,发送的时候端口号会自动从25切换成465

2、qq邮箱的host是smtp.exmail.qq.com

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值