邮件发送
来源:互联网 发布:淘宝联盟电脑版 编辑:程序博客网 时间:2024/04/30 17:44
现在邮件用的越来越强大了 ,各种通知都需要涉及到邮件,首先用户在本地搭建一个邮件服务器或者是拥有远程邮箱服务器的ip地址和端口号,以及连接时所需要的账号和密码。本地邮箱服务器你可以下载eyoumailserver.
首先需要导入jar文件 activation-1.1.jar和jar文件mail.jar
下面直接上代码
1.前台与后台的通信采用ajax
点击button
<button type="button" class="btn btn-primary" id="btnNotifyCustomerByEmail"><i class="fa fa-envelope-o"></i> Notify Customer by Email</button>
执行的js
- $("#btnNotifyCustomerByEmail").click(function () {
- if (!confirm("Are you sure to send a email to customer for notification?")) {
- return;
- }
- var orderNumber = $("#OrderNumber").val();
- var email = $("#txtCustomerTag").val();
- $.ajax({
- url: "<%=basePath%>orderList/NotifyCustomerByEmail",
- type: "post",
- dataType: "json",
- data: { orderNumber: orderNumber, email: email },
- async: false,
- success: function (data) {
- if (data.result == "1") {
- $("#msg").html(data.message);
- }
- else {
- alert(data.message);
- }
- }
- });
- })
- })
2.前台ajax访问controller里面的方法
- /**
- * 给用户发送order邮件
- *
- * @throws Exception
- */
- @RequestMapping("NotifyCustomerByEmail")
- public @ResponseBody String NotifyCustomerByEmail(String orderNumber, String email, HttpServletRequest request) {
- Subject subject = SecurityUtils.getSubject();
- Session session = subject.getSession();
- SystemUser user = (SystemUser) session.getAttribute(Const.SESSION_USER);
- //发送邮件同时给orderemailsent表中插入一条记录
- PageData ordersend=new PageData();
- ordersend.put("orderNumber", orderNumber);
- ordersend.put("sentBy", user.getsystemUserID());
- ordersend.put("sentDate", new Date());
- try {
- ordersend.put("OrderID", orderService.getOrderIDByNumber(ordersend));
- orderService.insertEmailSend(ordersend);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return orderService.notifyCustomerByEmail(orderNumber, email, request, user.getsystemUserID());
- }
3.service层的方法,主要用来封装数据,然后调用发送邮件的方法
- public String notifyCustomerByEmail(String orderNumber, String email, HttpServletRequest request,
- Integer systemUserId) {
- String method = new Exception().getStackTrace()[0].getClassName() + "."
- + new Exception().getStackTrace()[0].getMethodName() + "()";
- //Date date = new Date();
- //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
- MailSenderInfo mailSenderInfo = new MailSenderInfo();
- mailSenderInfo.setMailServerHost(Const.MAIL_SERVER);
- mailSenderInfo.setMailServerPort(Const.MAIL_PORT);
- mailSenderInfo.setUserName(Const.REQUEST_EMAIL);
- mailSenderInfo.setPassword(Const.REQUEST_PWD);
- mailSenderInfo.setValidate(true);
- mailSenderInfo.setSubject("Your order arrived at warehouse");
- mailSenderInfo.setContent("邮件内容");
- mailSenderInfo.setFromAddress(Const.REQUEST_EMAIL);
- mailSenderInfo.setToAddress(email);
- System.out.println(email);
- SimpleMailSender simpleMailSender = new SimpleMailSender();
- JSONObject jsonObject = new JSONObject();
- try {
- boolean flag = simpleMailSender.sendHtmlMail(mailSenderInfo);
- SystemLog log = new SystemLog();
- log.setCreatedDate(new Date());
- Integer orderId = findOrderByOrderNumber(orderNumber);
- log.setDescription("send notify success. orderId: " + orderId);
- log.setIp(PublicUtil.getRemoteHost(request));
- log.setMethodName(method);
- log.setSystemUserId(systemUserId);
- logService.SystemLog(log);
- if (flag) {
- jsonObject.put("result", 1);
- jsonObject.put("message", "Email has been sent successfully!");
- return jsonObject.toString();
- } else {
- jsonObject.put("result", 1);
- jsonObject.put("message", "Email send failed!");
- return jsonObject.toString();
- }
- } catch (Exception e) {
- e.printStackTrace();
- jsonObject.put("result", 1);
- jsonObject.put("message", "Email send failed!");
- return jsonObject.toString();
- }
- }
4.发送邮件封装的实体类
- package com.zipx.util.mail;
- /**
- *发送邮件需要使用的基本信息
- *
- */
- import java.util.Properties;
- public class MailSenderInfo {
- // 发送邮件的服务器的IP和端口
- private String mailServerHost;
- private String mailServerPort = "25";
- // 邮件发送者的地址
- private String fromAddress;
- // 邮件接收者的地址
- private String toAddress;
- // 登陆邮件发送服务器的用户名和密码
- private String userName;
- private String password;
- // 是否需要身份验证
- private boolean validate = false;
- // 邮件主题
- private String subject;
- // 邮件的文本内容
- private String content;
- // 邮件附件的文件名
- private String[] attachFileNames;
- /**
- * 获得邮件会话属性
- */
- public Properties getProperties(){
- Properties p = new Properties();
- p.put("mail.smtp.host", this.mailServerHost);
- p.put("mail.smtp.port", this.mailServerPort);
- p.put("mail.smtp.auth", validate ? "true" : "false");
- return p;
- }
- public String getMailServerHost() {
- return mailServerHost;
- }
- public void setMailServerHost(String mailServerHost) {
- this.mailServerHost = mailServerHost;
- }
- public String getMailServerPort() {
- return mailServerPort;
- }
- public void setMailServerPort(String mailServerPort) {
- this.mailServerPort = mailServerPort;
- }
- public boolean isValidate() {
- return validate;
- }
- public void setValidate(boolean validate) {
- this.validate = validate;
- }
- public String[] getAttachFileNames() {
- return attachFileNames;
- }
- public void setAttachFileNames(String[] fileNames) {
- this.attachFileNames = fileNames;
- }
- public String getFromAddress() {
- return fromAddress;
- }
- public void setFromAddress(String fromAddress) {
- this.fromAddress = fromAddress;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getToAddress() {
- return toAddress;
- }
- public void setToAddress(String toAddress) {
- this.toAddress = toAddress;
- }
- public String getUserName() {
- return userName;
- }
- public void setUserName(String userName) {
- this.userName = userName;
- }
- public String getSubject() {
- return subject;
- }
- public void setSubject(String subject) {
- this.subject = subject;
- }
- public String getContent() {
- return content;
- }
- public void setContent(String textContent) {
- this.content = textContent;
- }
- }
5.实现发送邮件的功能
- package com.zipx.util.mail;
- /**
- * 简单邮件(不带附件的邮件)发送器
- */
- import java.util.Date;
- import java.util.Properties;
- import javax.mail.Address;
- import javax.mail.BodyPart;
- import javax.mail.Message;
- import javax.mail.Multipart;
- import javax.mail.Session;
- import javax.mail.Transport;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeBodyPart;
- import javax.mail.internet.MimeMessage;
- import javax.mail.internet.MimeMultipart;
- import com.zipx.controller.base.BaseController;
- public class SimpleMailSender extends BaseController {
- /**
- * 以HTML格式发送邮件
- * @param mailInfo 待发送的邮件信息
- */
- public boolean sendHtmlMail(MailSenderInfo mailInfo) throws Exception{
- // 判断是否需要身份认证
- MyAuthenticator authenticator = null;
- Properties pro = mailInfo.getProperties();
- //如果需要身份认证,则创建一个密码验证器
- if (mailInfo.isValidate()) {
- authenticator = new MyAuthenticator(mailInfo.getUserName(), mailInfo.getPassword());
- }
- // 根据邮件会话属性和密码验证器构造一个发送邮件的session
- Session sendMailSession = Session.getDefaultInstance(pro,authenticator);
- // 根据session创建一个邮件消息
- Message mailMessage = new MimeMessage(sendMailSession);
- // 创建邮件发送者地址
- Address from = new InternetAddress(mailInfo.getFromAddress());
- // 设置邮件消息的发送者
- mailMessage.setFrom(from);
- // 创建邮件的接收者地址,并设置到邮件消息中
- Address to = new InternetAddress(mailInfo.getToAddress());
- // Message.RecipientType.TO属性表示接收者的类型为TO
- mailMessage.setRecipient(Message.RecipientType.TO,to);
- //设置密送
- Address bcc=new InternetAddress(Const.MAIL_BCC);
- mailMessage.setRecipient(Message.RecipientType.BCC,bcc);
- // 设置邮件消息的主题
- mailMessage.setSubject(mailInfo.getSubject());
- // 设置邮件消息发送的时间
- mailMessage.setSentDate(new Date());
- // MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
- Multipart mainPart = new MimeMultipart();
- // 创建一个包含HTML内容的MimeBodyPart
- BodyPart html = new MimeBodyPart();
- // 设置HTML内容
- html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
- mainPart.addBodyPart(html);
- // 将MiniMultipart对象设置为邮件内容
- mailMessage.setContent(mainPart);
- // 发送邮件
- Transport.send(mailMessage);
- return true;
- }
- package com.zipx.util.mail;
- /**
- *
- */
- import javax.mail.*;
- public class MyAuthenticator extends Authenticator{
- String userName=null;
- String password=null;
- public MyAuthenticator(){
- }
- public MyAuthenticator(String username, String password) {
- this.userName = username;
- this.password = password;
- }
- protected PasswordAuthentication getPasswordAuthentication(){
- return new PasswordAuthentication(userName, password);
- }
- }
0 0
- 邮件发送
- 邮件发送
- 发送邮件
- 发送邮件
- 发送邮件
- 邮件发送
- 邮件发送
- 邮件发送
- 发送邮件
- 发送邮件
- 邮件发送
- 邮件发送
- 发送邮件
- 邮件发送
- 邮件发送
- 发送邮件
- 发送邮件
- 发送邮件
- LIS hdu 5748 (Bellovin)
- hdoj1159Common Subsequence(LCS 最长公共子序列)
- DS18B20
- 使用OSGI+MQ的方式解决集中化运维问题
- HDU 1394 Minimum Inversion Number
- 邮件发送
- 判断CPU大小端
- codeforces 691C Exponential notation(思维 + 比较精妙的模拟)
- 【Android】Android Stdio创建App控件
- matlab文件夹前带加号表示是包package
- Struts2实现下载文件
- linux下的信号列表
- 个人网站 有兴趣的可以看看!
- Java中Runnable和Thread的区别