0
点赞
收藏
分享

微信扫一扫

Java 实现邮件发送

洛茄 2023-09-26 阅读 33

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.codehaus.jettison.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;

public class Main {
    public static void main(String[] args) {
        // 接收邮件的人
    	String eamilTo = "xxx@qq.com, aaa@qq.com"; // 需要填写多个人用逗号分开
    	// 邮件抄送
    	String emailCs = ""; // 需要填写多个人用逗号分开

		// 文件路径
		String filePath = "http://your_server_url";
		
		// 发送邮件
		sendEmail(emailTo, eamilCss, filePath);
    }
	
	private static void sendEmail(String emailTo, String emailCs, String outputFile){
		 String emailApiUrl = "http://example.com/api"; // 替换为实际的API地址
		 CloseableHttpClient httpClient = HttpClients.createDefault();
		 HttpPost post = new HttpPost(emailApiUrl);
		 String[] sendEmailTo = emailTo.split(",");
		 String[] sendEmailCcs = emailCs.split(",");
         String filePath = outputFile + ".zip";
     
 		 
		 String responseContent = null;
		 CloseableHttpResponse response = null;

         try {
         		// 构建JSONObject对象
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("subject","测试邮件");
				jsonObject.put("text","这是一封测试邮件");
				jsonObject.put("to", sendEmailTo);
				jsonObject.put("ccs",sendEmailCcs);
				jsonObject.put("filepath",filePath);
				jsonObject.put("filepathType","test");
				jsonObject.put("status","End");
				
				post.setHeader("Content-Type","application/json");
		 		post.setEntity(new StringEntity(data, "UTF-8"));

 				response = client.execute();
 				if(response.getStatusLine().getStatusCode() == 200) {
					HttpEntity entity = response.getEntity();
					responseContent = EntityUtils.toString(entity, "UTF-8");
				}
		 } catch (Exception e) {
		 	e.printStackTrace();
		 }
	}

}

后端实体类 EmailInfo.java

@Data
@NoArgsConstructor
public class EmailInfo {
	// 主题(标题)
	private String subject;

    // 正文
    private String text;

   // 抄送人
   private String[] ccs;

   // 收件人
   private String[] to;

   // 附件路径
   private String filepath;

   // 附件路径类型
   private String filepathType;

   // 任务状态
   private String status;
}

核心代码

public void sendEmail(EmailInfo emailInfo) {
	Date date = new Date();
	if(Contant.END.equals(emailInfo.getStatus())) {
			try {
			 		MimeMessage mimeMessage = javaMailSender.createMimeMessage();
			 		MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
			 		mimeMessageHelper .setFrom(from); 
			 		mimeMessageHelper .setTo(emailInfo.getTo());
			 		mimeMessageHelper.setSubject(simpleDateFormat.format(date) + " " + emailInfo.getSubject());
			 		mimeMessageHelper.setText(emailInfo.getText(), true);
			 		if(emailInfo.getCss() != null) {
						mimeMessageHelper.setCss(emailInfo.getCss());
					}
					if(emailInfo.getFilePath() != null) {
						String[] subStrings = emailInfo.getFilePath().split(",");
						int numCommas = subStrings.length - 1;
						for(int i = 0; i <= numCommas; i++) {
							addAttachment(subStrings[i], emailInfo.getFilepathType(), mimeMessageHelper);
						}
					}
					javaMailSender.send(mimeMessageHelper.getMimeMessage());
            } catch (MessageException messagingException) {
				log.error("邮件发送失败:" + messagingException.getMessage());
			} catch (IOException e) {
				log.error(e.getMessage());
				throw new RuntimeException(e);
			}
     }

}

inputStream 转 file 方法

private void inputStramFile(InputStram is, File file) throws IOException{
	try (FileOutputStream outputStream = new FileoutputStream(file)) {
		byte[] buffer = new byte[4096];
		int bytesRead;
		while ((bytesRead = is,read(buffer) != -1)){
			outputStream.write(buffer, 0, bytesRead);
		}
		outputStream.close();
		is.close();
	}

}

添加附件方法

private void addAttachement(String filePath, String filePathType, MimeMessageHelper mimeMessageHelper) throws IOException, MessageException {
	URL url = new URL(downloadUrl + filePaht + "&type=" + filePathType);
	HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	InputStram inputStream = conn.getInputStream();
	Path uploadDir = Paths.get(targetFolder).toAbsolutePath().normalize();
	FIle targetFile = new File(uploadDir.toString(), filePath.substring(filePaht.lastIndexOf("/") + 1));
	inputStreamFile(inputStream, targetFile);
	mimeMessageHelper.addAttachment(filePath.substring(filePaht.lastIndexOf("/") + 1), targetFile);
	
}

一点困惑:

在HTTP的POST请求中,无法直接识别JSONObject对象中的中文文件路径。这是因为HTTP协议规定,在发送请求时,URL和请求头中只能包含ASCII字符,而不能包含非ASCII字符(如中文字符)或特殊字符。

如果需要传递中文文件路径,可以考虑对中文文件路径进行编码,然后将编码后的路径作为参数传递给服务器端。常用的编码方式有URL编码(Percent-encoding),可以使用Java中的URLEncoder类对中文进行编码。

例如,将中文文件路径 "/路径/文件.txt" 进行URL编码,可以得到 "%2F%E8%B7%AF%E5%BE%84%2F%E6%96%87%E4%BB%B6.txt" ,然后将编码后的路径作为参数通过POST请求提交给服务器端。

在服务器端接收到请求后,需要对收到的URL参数进行解码,可以使用Java中的URLDecoder类对URL进行解码,还原为原始的中文文件路径。

请注意,保证服务器端和客户端的编解码方式一致,以免发生乱码或路径错误的情况。



举报

相关推荐

0 条评论