1. java使用公司邮件服务器发送邮件
1 /** 2 * 发送邮件 3 */ 4 public void sendMail(String receivers, String content, String title) { 5 try { 6 // 公司邮件服务器地址 7 URL url = new URL("公司邮件服务器地址"); 8 // 设置connection 9 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 10 connection.setDoOutput(true); 11 connection.setDoInput(true); 12 connection.setRequestMethod("POST"); 13 connection.setUseCaches(false); 14 connection.setInstanceFollowRedirects(true); 15 connection.setRequestProperty("Content-Type", "application/json"); 16 connection.setRequestProperty("Connection", "Keep-Alive"); 17 connection.connect(); 18 // 设置邮件接收人,标题,内容 19 DataOutputStream out = new DataOutputStream(connection.getOutputStream()); 20 Map<String, String> jsonMap = new HashMap<String, String>(3); 21 jsonMap.put("to", receivers); //邮件接收人 22 jsonMap.put("subject", convertToISO_8859_1(title)); // 邮件主题 23 jsonMap.put("content", convertToISO_8859_1(content)); // 邮件正文 24 JSONObject jsonObj = JSONObject.fromObject(jsonMap); 25 // 发送 26 out.writeBytes(jsonObj.toString()); 27 out.flush(); 28 out.close(); 29 // 返回内容 30 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); 31 String result = ""; 32 String line; 33 while ((line = reader.readLine()) != null) { 34 result += line; 35 } 36 // 日志记录邮件返回内容 37 if (logger.isInfoEnabled()) { 38 logger.info(result); 39 } 40 // 解析返回内容 41 JSONObject resultJSON = JSONObject.fromObject(result); 42 String code = resultJSON.getString("code"); 43 if ("200".equals(code)) {// 200表示发送成功,如果发送成功则删除临时表数据 44 logger.info("发送邮成功!"); 45 } else { 46 logger.info("发送邮件失败,等待下次发送!"); 47 } 48 49 } catch (MalformedURLException e) { 50 logger.error("邮件发送失败", e); 51 52 } catch (IOException e) { 53 logger.error("邮件发送失败", e); 54 } 55 }
时间: 2024-10-08 16:57:20