12.短信,邮件发送案例

短信,邮件发送案例

导入响应的包

12.短信,邮件发送案例

controller

package com.zb.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Random;

import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

@WebServlet("/user")
public class UserInfoController extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req,resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		String op = req.getParameter("op");
		
		System.out.println(op);
		
		if("ssm".equals(op)) {
			String phoneNumber = req.getParameter("pn");
			
			Random rd = new Random();
			int checkCode = rd.nextInt(10)*100000+rd.nextInt(10)*10000+rd.nextInt(10)*1000+rd.nextInt(10)*100+rd.nextInt(10)*10+rd.nextInt(10);
			System.out.println(checkCode);
			//this.sendShortMessage(phoneNumber,checkCode);
			req.getSession().setAttribute("checkCode", checkCode);
		}else if("se".equals(op)) {
			//用户在页面上输入的验证码
			String ssmCode = req.getParameter("checkCode");
			//在第一次发送短息的时候生成的验证码
			String checkCode = ((Integer)req.getSession().getAttribute("checkCode"))+"";
			//判断两次输入验证码是否一致
			if(checkCode.equals(ssmCode)) {
				String userEmail = req.getParameter("userEmail");
				String userPwd = "123456";
				String phoneNumber = req.getParameter("userPhoneNumber");
				int userStatus = 0;
				
				try {
					this.saveUser(userEmail, userPwd, phoneNumber, userStatus);
				} catch (Exception e1) {
					System.out.println(e1);
					resp.getWriter().print("zhuce shibai!");
				}
				
				String basePath = req.getScheme()+"://"+req.getServerName()+":"+req.getServerPort()+req.getContextPath()+"/";
				String imgUrl = basePath+"img/timg.jpg";
				String jhUrl = basePath+"user?op=jh&email="+userEmail;
				String content = "<h3><a href='"+jhUrl+"'>点击激活</a><h3><img src='http://127.0.0.1:8080/javaWebSenior/img/timg.jpg'>";
				resp.setCharacterEncoding("UTF-8");
				resp.setContentType("text/html;charset=UTF-8");
				try {
					this.sendEmail(userEmail, content);
				} catch (MessagingException e) {
					e.printStackTrace();
				}
			}else{
				resp.getWriter().print("liangci yanzhengma buyizhi!");
			}
		}else if("jh".equals(op)) {
			String userEmail = req.getParameter("email");
			System.out.println(userEmail);
			try {
				this.updateUserByEmail(userEmail);
			} catch (Exception e) {
				resp.getWriter().print("jihuo yichang!");
			}
		}
	}
	
	public void sendShortMessage(String phoneNumber,int checkCode) {
		//设置访问秘钥
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "","" );
		//创建阿里云短信客户端
		IAcsClient client = new DefaultAcsClient(profile);
		//创建阿里云请求
		CommonRequest request = new CommonRequest();
		request.setSysMethod(MethodType.POST);
		request.setSysDomain("dysmsapi.aliyuncs.com");
		request.setSysVersion("2017-05-25");
		request.setSysAction("SendSms");
		request.putQueryParameter("RegionId", "cn-hangzhou");
		//设置发送的电话号码
		request.putQueryParameter("PhoneNumbers", phoneNumber);
		//设置使用的短信签名
		request.putQueryParameter("SignName", "足下Java就业班");
		//设置使用的短信模板
		request.putQueryParameter("TemplateCode", "SMS_200693215");
		//设置发送的code
		request.putQueryParameter("TemplateParam", "{\"code\":\""+checkCode+"\"}");
		try {
			CommonResponse response = client.getCommonResponse(request);
			System.out.println(response.getData());
		} catch (ServerException e) {
			e.printStackTrace();
		} catch (ClientException e) {
			e.printStackTrace();
		}
	}
	
	public void sendEmail(String address,String content) throws MessagingException {
		//设置发送属性
		Properties props = new Properties();
		//设置发送服务器
		props.put("mail.host", "smtp.qq.com");
		//设置发送协议
		props.put("mail.transport.protocol", "smtp");
		//服务器端口号
		props.put("mail.smtp.port","25");
		//是否进行安全验证
		props.put("mail.smtp.auth", "true");
		//创建于邮件服务器的会话
		Session mailSession = Session.getInstance(props);
		//调试模式,查看发送状态
		mailSession.setDebug(true);
		//创建邮件传输对象
		Transport t = mailSession.getTransport();
		//连接邮件服务器
		t.connect("smtp.qq.com", "@qq.com", "");
		//发件人/收件人
		InternetAddress formId = new InternetAddress("@qq.com");
		InternetAddress toId = new InternetAddress(address);
		//创建一封邮件
		Message message = new MimeMessage(mailSession);
		//设置发件人
		message.setFrom(formId);
		//设置收件人
		message.setRecipient(RecipientType.TO, toId);
		//标题
		message.setSubject("Java53激活信息");
		//内容
		message.setContent(content,"text/html;charset=UTF-8");
		//发送邮件
		t.sendMessage(message, message.getAllRecipients());
	}
	
	public void saveUser(String email,String password,String phoneNumber,int s) throws Exception {
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn = DriverManager.getConnection("jdbc:mysql:///user_info?characterEncoding=UTF-8", "root", "123456");
		PreparedStatement pst = conn.prepareStatement(" INSERT INTO user_info VALUES (DEFAULT,?,?,?,?) ");
		pst.setString(1, email);
		pst.setString(2, password);
		pst.setString(3, phoneNumber);
		pst.setInt(4, s);
		pst.executeUpdate();
		pst.close();
		conn.close();
	}
	
	public void updateUserByEmail(String email) throws Exception {
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn = DriverManager.getConnection("jdbc:mysql:///user_info?characterEncoding=UTF-8", "root", "123456");
		PreparedStatement pst = conn.prepareStatement(" UPDATE user_info SET user_status = 1 WHERE user_email = ? ");
		pst.setString(1, email);
		pst.executeUpdate();
		pst.close();
		conn.close();
	}
}
上一篇:java:JDBC使用步骤(mysql)java小白的第一篇博客


下一篇:基于JDBC进行数据库的增删改查