Java Web realizes mail sending function

Mail sending function based on JavaWeb (multiple attachments) for your reference. The specific contents are as follows

The main purpose of this study is to test the function realization of sending from QQ mailbox to any valid mailbox, with multiple attachments. Learners can learn from other email formats and sort out the content to be written. The project puts the file content into the mimemessage mail object, which contains some contents such as sender, recipient, CC, mail subject, mail content, mail time and mail attachments.

Problems encountered in the project:

1. When executing to file file = new file ("D: \ chat_software \ sky. JPG"); When an error occurs, the xlsx file written before can be updated during the test Xls, JPG, text Send doc file. An error occurred while sending xlsx files. Problem solution: The XLS file extension corresponds to Microsoft Office Excel 2003 and earlier The xlsx file extension corresponds to Microsoft Office Excel 2007 and later versions. If possible, the Mai you downloaded is not above 1.6. It is recommended to download mail above 1.6

2. Execute to message saveChanges(); Method reports an error and cannot save the settings. It may also be caused by your lower mail version.

Write file = new file(); Pay attention to modifying the correct path. You can also write it in the form form and use file to transfer the value. The subject and content are also written in the method. It varies from person to person. If other needs, you can change the parameters to transfer the value.

The main jar packages used this time are as follows:

The code is as follows:

EmailSendController. java

package com.yang.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yang.util.Email_Send_Util;

@Controller
@RequestMapping("/email")
public class EmailSendController {

 @RequestMapping(value = "/send.do")
 @ResponseBody
 public boolean impotr(HttpServletRequest request) {
 String toMail = request.getParameter("toMail");
 String myMail = request.getParameter("myMail");
 String userPwd = request.getParameter("userPwd");

 System.out.println( toMail+myMail+userPwd);
 boolean bool=Email_Send_Util.send( toMail,myMail,userPwd);
 return bool ;
 }

}

Authentication. java

package com.yang.util;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

public class Authentication extends Authenticator {
 String username = null;
 String password = null;

 public Authentication() {
 }

 public Authentication(String username,String password) {
  this.username = username;
 this.password = password;
 }

 protected PasswordAuthentication getpasswordAuthentication(){
 PasswordAuthentication pa = new PasswordAuthentication(username,password);
 return pa;
 }
}

CreateMimeMessage. java

package com.yang.util;

import java.io.File;
import java.util.Date;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message.RecipientType;
import javax.mail.Address;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

/**
 * 创建一封复杂邮件(文本+图片+附件)
 */
public class CreateMimeMessage {
 public static MimeMessage createMimeMessage(Session session,String myMail,String toMail) throws Exception {
 // 1. 创建邮件对象
 MimeMessage message = new MimeMessage(session);

 // 2. From: 发件人
 message.setFrom(new InternetAddress(myMail,"我的测试邮件_发件人昵称","UTF-8"));

 // 3. To: 收件人(可以增加多个收件人、抄送、密送)
 message.addRecipient(RecipientType.TO,new InternetAddress(toMail,"我的测试邮件_收件人昵称","UTF-8"));

 // 4. Subject: 邮件主题
 message.setSubject("TEST邮件主题(文本+图片+附件)","UTF-8");

 // 抄送人
 Address ccAddress = new InternetAddress("*********@qq.com","我的测试邮件_抄送人昵称","UTF-8");
 message.addRecipient(Message.RecipientType.CC,ccAddress);

 /*
 * 下面是邮件内容的创建:
 */

 // 5. 创建图片“节点”
 MimeBodyPart image = new MimeBodyPart();
 File file = new File("D:\\Chat_Software\\sky.JPG");
 DataHandler dh = new DataHandler(new FileDataSource(file)); // 读取本地文件
 image.setDataHandler(dh); // 将图片数据添加到“节点”
 // image.setContentID("image_fairy_tail");// 为“节点”设置一个唯一编号(在文本“节点”将引用该ID)
 image.setFileName(MimeUtility.encodeText(file.getName()));

 // 6. 创建文本“节点”
 MimeBodyPart text = new MimeBodyPart();
 // text.setContent("这是一张图片<br/>测试图片<br/><img
 // src='cid:image_fairy_tail'/>","text/html;charset=UTF-8");
 text.setContent("这是一张图片<br/>测试图片","text/html;charset=UTF-8");

 // 7. (文本+图片)设置 文本 和 图片 “节点”的关系(将 文本 和 图片 “节点”合成一个混合“节点”)
 MimeMultipart mm_text_image = new MimeMultipart();
 mm_text_image.addBodyPart(text);
 mm_text_image.addBodyPart(image);
 mm_text_image.setSubType("related"); // 关联关系

 // 8. 将 文本+图片 的混合“节点”封装成一个普通“节点”
 // 最终添加到邮件的 Content 是由多个 BodyPart 组成的 Multipart,所以我们需要的是 BodyPart,// 上面的 mm_text_image 并非 BodyPart,所有要把 mm_text_image 封装成一个 BodyPart
 MimeBodyPart text_image = new MimeBodyPart();
 text_image.setContent(mm_text_image);

 // 9. 创建附件“节点”
 MimeBodyPart attachment = new MimeBodyPart();
 File file2 = new File("E:\\boHaiBank\\Test\\test.xlsx");
 DataHandler dh2 = new DataHandler(new FileDataSource(file2)); // 读取本地文件
 attachment.setDataHandler(dh2); // 将附件数据添加到“节点”
 attachment.setFileName(MimeUtility.encodeText(dh2.getName())); // 设置附件的文件名

 // 10. 设置(文本+图片)和 附件 的关系(合成一个大的混合“节点” / Multipart )
 MimeMultipart mm = new MimeMultipart();
 mm.addBodyPart(text_image);
 mm.addBodyPart(attachment); // 如果有多个附件,可以创建多个多次添加
 mm.setSubType("mixed"); // 混合关系

 // 11. 设置整个邮件的关系(将最终的混合“节点”作为邮件的内容添加到邮件对象)
 message.setContent(mm);

 // 12. 设置发件时间
 message.setSentDate(new Date());

 // 13. 保存上面的所有设置
 message.saveChanges();

 return message;
 }

}

Email_ Send_ Util. java

package com.yang.util;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;

public class Email_Send_Util {

 public static boolean send(String toMail,String userPwd) {
 // QQ邮箱发件的服务器和端口
 Properties props = new Properties();

 props.put("mail.transport.protocol","SMTP");// 设置发送邮件使用的协议
 props.put("mail.smtp.host","smtp.qq.com");// 指定邮件发送服务器服务器 "smtp.qq.com"
 props.put("mail.smtp.port","25");
 props.put("mail.smtp.auth","true"); // 设置需要身份验证(不验证会不通过)

 Authenticator authentication = new Authentication(myMail,"你的邮箱授权码");
 Session session = Session.getDefaultInstance(props,authentication);

 MimeMessage message;
 try {
 message = CreateMimeMessage.createMimeMessage(session,toMail);
 // 获取发送方对象
 Transport transport = session.getTransport("smtp");
 // 连接邮件服务器,链接您的QQ邮箱,用户名(可以不用带后缀)、密码
 transport.connect(myMail,userPwd);
 // 发送邮件
 // 第一个参数:邮件的消息体
 // 第二个参数:邮件所有的接收人/抄送人
 transport.sendMessage(message,message.getAllRecipients());
 transport.close();
 return true;
 } catch (Exception e) {
 e.printStackTrace();
 return false;
 }
 }

}

Test the JSP page that sends the mailbox

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
 String path = request.getContextPath();
 String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
 + path + "/";
%>
<html>
<head>
<Meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>邮件发送</title>

<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script>

</head>
<body>
 <div>
 <form id="login_form" method="post">
 <table border="1px" width="750px" height="400px" align="center" cellpadding="0px" cellspacing="0px" bgcolor="white" >
 <tr height="40px">
 <td colspan="2">
 <font size="4">邮件发送</font>    Email
 </td>
 </tr>
 <tr>
  <td>收件人</td><td><input type="text" name="toMail" size="34px"/></td>
 </tr>
 <tr>
  <td>邮件发送人</td><td><input type="text" name="myMail" size="34px"/></td>
 </tr>
 <tr>
  <td>密码</td><td><input type="text" name="userPwd" size="34px"/></td>
 </tr>

 </table>
 <input type="button" onclick="emailsend()" value="发送">
 </form>
 </div>
 <script type="text/javascript">

 function emailsend() {
 $.ajax({
 url : "email/send.do",type : "POST",data : $("#login_form").serialize(),beforeSend : function() {
  console.log("正在进行,请稍候");
 },success : function(e) {
  if (e == true) {
  alert("发送成功");
  } else {
  alert("发送失败");
  }
 }
 });
 }
 </script>
</body>
</html>

After sending successfully, the recipient's message

The required jar package can be downloaded from this link, including the jar package required to send mail regularly: mail jar

The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>