java邮件发送功能

5 篇文章 0 订阅
1 篇文章 0 订阅

前言:邮件发送功能是在开发过程中经常用到的,一个代办信息的产生,通常需要发邮件进行通知。

1.引入java-mail所用的.jar包。

2.获取邮件的配置

final Properties props = new Properties();

props.put("mail.smtp.host", ip);// 指定SMTP服务器ip

props.put("mail.smtp.port", port);// 指定SMTP服务器端口

props.put("mail.smtp.auth", "true");// 指定是否需要SMTP验证

props.put("mail.transport.protocol","smtp");//协议

props.put("mail.user",username);//用户名

props.put("mail.password", password);//密码

3.构建授权信息,用户进行smtp进行身份验证

Authenticator auth = new Authenticator() {

@Override

protected javax.mail.PasswordAuthentication getPasswordAuthentication() {

  String userName = props.getProperty("mail.user");

  String password = props.getProperty("mail.password");

  return new PasswordAuthentication(userName, password);

       }

     };

4.获取mailSession对象(javax.mail.Session保存邮件系统的配置属性和提供用户验证的信息)

                 Session mailSession = null;

                mailSession = Session.getInstance(props,auth);

                mailSession.setDebug(false);// 是否在控制台显示debug信息

5.获取邮件的发件人、收件人、邮件内容等

               MimeMessage message = new MimeMessage(mailSession);

                message.setFrom(new InternetAddress(mailSender.getUserName()));// 发件人

                // 创建邮件的接收者地址,并设置到邮件消息中

                String[] recevieAddress = mailObject.getRecevieAddress();

                Address[] tos = new InternetAddress[recevieAddress.length];

                for (int i = 0; i < recevieAddress.length; i++) {

                    tos[i] = new InternetAddress(recevieAddress[i]);

                }

                message.addRecipients(Message.RecipientType.TO, tos);// 收件人

                // 设置邮件内容

                message.setContent(content, "text/html;charset=UTF-8");

                // 邮件主题

                message.setSubject(subject());

                message.saveChanges();

6.发送邮件

                Transport transport = mailSession.getTransport();

                transport.connect();

                transport.sendMessage(message, message.getAllRecipients());

                transport.close();

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值