Email_demo

步骤一:

package com.bw.pojo;

public class MyEmail {
    private static MyEmail email;
    private String host = "smtp.163.com";    // 发送方邮箱host
    private String from = "17600246280@163.com";   // 发送方邮箱
    private String user = "17600246280";   // 发送方邮箱账号
    private String pwd = "ovel1314.21";     // 发送方邮箱密码


    public static MyEmail getEmail(){
        if(email!=null){
            return email;
        }else{
            email = new MyEmail();
            return email;
        }
    }
    public String getFrom() {
        return from;
    }

    public String getUser() {
        return user;
    }

    public String getPwd() {
        return pwd;
    }

    public String getHost() {
        return host;
    }
}


步骤二:

package com.bw.service;

public interface ISendEmailService {
    /**
     * 写一个发送邮件的方法
     * @param content
     * @param title
     * @param address
     * @param affix
     * @param affixName
     */
    void send(String content, String title, String address, String affix, String affixName);
}


实现类:
package com.bw.service.Impl;



import com.bw.pojo.MyEmail;
import com.bw.service.ISendEmailService;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class SendEmailServiceImpl implements ISendEmailService {

    @Override
    public void send(String content, String title, String address, String affix, String affixName) {
        MyEmail myEmail = MyEmail.getEmail();
        String host = myEmail.getHost();
        String user = myEmail.getUser();
        String pwd = myEmail.getPwd();
        String from = myEmail.getFrom();


        Properties props = new Properties();

        // 设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器)  -->需要修改
        props.put("mail.smtp.host", host);
        // 需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条)
        props.put("mail.smtp.auth", "true");

        // 用刚刚设置好的props对象构建一个session
        Session session = Session.getDefaultInstance(props);

        // 有了这句便可以在发送邮件的过程中在console处显示过程信息,供调试使
        // 用(你可以在控制台(console)上看到发送邮件的过程)
        session.setDebug(true);

        // 用session为参数定义消息对象
        MimeMessage message = new MimeMessage(session);
        try {
            // 加载发件人地址   -->需要修改
            message.setFrom(new InternetAddress(from));
            // 加载收件人地址   -->需要修改
            message.addRecipients(Message.RecipientType.TO, address);
            List<InternetAddress> list = new ArrayList();//不能使用string类型的类型,这样只能发送一个收件人
            String []median=address.split(",");//对输入的多个邮件进行逗号分割
            for(int i=0;i<median.length;i++){
                list.add(new InternetAddress(median[i]));
            }
            InternetAddress[] addresses =(InternetAddress[])list.toArray(new InternetAddress[list.size()]);
            message.addRecipients(Message.RecipientType.TO, addresses);
            // 加载标题   --->也需要修改
            message.setSubject(title);

            // 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
            Multipart multipart = new MimeMultipart();

            // 设置邮件的文本内容
            BodyPart contentPart = new MimeBodyPart();
            //需要修改的地方   写的内容
            contentPart.setText(content);

            multipart.addBodyPart(contentPart);
            // 添加附件
            if(affix != null && !"".equals(affix))
            {
                BodyPart messageBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(affix);
                // 添加附件的内容
                messageBodyPart.setDataHandler(new DataHandler(source));
                // 添加附件的标题
                // 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
                sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
                messageBodyPart.setFileName("=?GBK?B?"+ enc.encode(affixName.getBytes()) + "?=");
                multipart.addBodyPart(messageBodyPart);
            }

            // 将multipart对象放到message中
            message.setContent(multipart);
            // 保存邮件
            message.saveChanges();
            // 发送邮件
            Transport transport = session.getTransport("smtp");
            // 连接服务器的邮箱
            transport.connect(host, user, pwd);
            // 把邮件发送出去
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


步骤三:

package com.bw.controller;

import com.bw.pojo.User;
import com.bw.service.IUserService;
import com.bw.util.FileUtil;
import com.bw.util.RandomUtil;
import com.bw.util.TwoDimensionCode;
import com.google.zxing.WriterException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService iUserService;

    //查询所有
    @RequestMapping("selUser")
    public ModelAndView selUser(ModelAndView modelAndView) throws  Exception{
     List<User> userList=   iUserService.selUser();
    modelAndView.addObject("userList",userList);
    modelAndView.setViewName("show");
        return modelAndView;
    }


    //模糊查询
    @RequestMapping("fuzzyUser")
    public ModelAndView fuzzyUser(ModelAndView modelAndView,String name){
        List<User> fuzzyUser=   iUserService.fuzzyUser(name);
        modelAndView.addObject("fuzzyUser",fuzzyUser);
        modelAndView.setViewName("show");
        return modelAndView;
    }


    //注册
    @RequestMapping("registerUser")
    public ModelAndView registerUser(@RequestParam(value = "file",required = false)MultipartFile file, HttpServletRequest request, ModelAndView modelAndView, User user)throws Exception{
        if (!file.isEmpty()){
            String headPhoto= FileUtil.uploadFile(file,request);
            user.setName(headPhoto);
        }else {
            user.setName(null);
        }
        iUserService.registerUser(user);
        modelAndView.setViewName("redirect:/user/selUser.action");
        return modelAndView;
    }

     //发送二维码验证
     @RequestMapping(value = "sendCode",method = RequestMethod.GET)
     @ResponseBody
     public Map<String,Object> sendCode(String email) throws IOException, WriterException {
         String title="XXX资讯后台管理系统";
         String code= RandomUtil.getStringRandom();
         String content="欢迎注册本平台,你的验证码是:"+code;
         TwoDimensionCode.QRCodeTest qrCodeTest = new TwoDimensionCode.QRCodeTest();
         qrCodeTest.testEncodeToEmail(content,300,300,"piao","png",title,email);
         Map<String,Object> map=new HashMap<>();
         map.put("checkCode",code);
         return map;
     }

    //检查邮箱是否重复
    @RequestMapping(value = "/checkEmail",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> checkEmail(String email){
        Map<String,Object> map=new HashMap<>();
        map.put("flag","邮箱没有重复!");
        return map;
    }

    //批量删除
    @RequestMapping("batchUser")
    public ModelAndView batchUser(ModelAndView modelAndView,String ids){
        iUserService.batchUser(ids);
        modelAndView.setViewName("show");
        return modelAndView;
    }
}


步骤四:

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/9/21/021
  Time: 15:31
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" isELIgnored="false" %>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
%>
<html>
<head>
    <title>Title</title>
    <script src="/resources/jquery/jquery-1.8.3.js"></script>
    <script>
        function sendCode() {
            var email=$("#eml").val();
            $.ajax({
                type: "get",
                url: "/user/sendCode.action",
                data: {email:email},
                dataType: "json",
                success: function (data) {
                    alert("验证码已发送到你的邮箱");
                    $("#code2").val(data.code);
                },
                error: function () {
                    alert("系统繁忙,请稍后重试");
                }
            });
        }
    </script>
</head>
<body>
<h2>首页</h2>
<form action="/user/registerUser.action" enctype="multipart/form-data" method="post">
    上传图片:<input type="file" name="file" /><br>
    用户邮箱:<input type="text" name="email" id="eml"/><br>
    用户Miami:<input type="text" name="password"/><br>
    用户余额:<input type="text" name="balance" /><br>
    <input type="button" value="获取验证码" οnclick="sendCode()"/>
    <input type="submit" value="注册" />
</form>
</body>
</html>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用\[1\]:根据提供的引用内容,错误信息"Error: unknown format “email” ignored in schema at path "#/properties/name""是因为在使用"format"方法时,没有引入相应的模块。解决方法是在使用该方法的文件下,引入相应的模块,如下所示: ```javascript const Ajv = require('ajv') const addFormats = require('ajv-formats') const ajv = new Ajv() addFormats(ajv) ``` 引用\[3\]:根据提供的引用内容,给出的是一个完整的代码示例。根据代码,可以看出这是一个使用Ajv库进行数据验证的代码。在代码中,定义了一个schema对象,其中包含了对"name"属性的验证规则,包括类型为字符串和格式为"email"。然后使用Ajv库的compile方法编译schema,并使用validate方法对数据进行验证。如果验证不通过,则输出错误信息。根据提供的代码,没有涉及到C/C++相关的内容,因此无法回答关于C/C++的问题。 #### 引用[.reference_title] - *1* *3* [解决Error: unknown format “email“ ignored in schema at path “#/properties/name](https://blog.csdn.net/qq_42943107/article/details/123609869)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [PS C:\Users\Administrator> npm install -g cnpm --registry=...](https://blog.csdn.net/weixin_35750483/article/details/129526222)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值