• SMTP 发送邮件


    package com.chengyi.common.service;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.UnsupportedEncodingException;
    import java.util.Properties;
    
    import javax.activation.DataHandler;
    import javax.activation.DataSource;
    import javax.mail.Authenticator;
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.AddressException;
    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;
    import javax.mail.util.ByteArrayDataSource;
    
    import org.springframework.stereotype.Service;
    
    @Service
    public class MailService {
    
    	// 发送邮件String emailMsg,String users
    	public static void sendMail(String users, String msg, String title, String passWord) throws AddressException, MessagingException, UnsupportedEncodingException {
    
    		Message message = initMailInfo(passWord);
    
    		new InternetAddress();
    		InternetAddress[] internetAddressTo = InternetAddress.parse(users);
    
    		// 设置发送方式与接收者多人
    		message.setRecipients(MimeMessage.RecipientType.TO, internetAddressTo);
    		// 设置主题
    		message.setSubject(title);
    		// 设置内容
    		message.setContent(msg, "text/html;charset=utf-8");
    
    		// 3.创建 Transport用于将邮件发送
    		Transport.send(message);
    	}
    
    	private static Message initMailInfo(String passWord) throws AddressException, MessagingException {
    		// 1.创建一个程序与邮件服务器会话对象 Session
    		Properties props = new Properties();
    		props.setProperty("mail.transport.protocol", "SMTP");
    		props.setProperty("mail.smtp.host", "***");
    		props.setProperty("mail.smtp.port", "**");
    		props.setProperty("mail.smtp.ssl.enable", "true");
    		// 指定验证为true
    		props.setProperty("mail.smtp.auth", "true");
    		props.setProperty("mail.smtp.timeout", "12000");
    		// 验证账号及密码,密码需要是第三方授权码
    		Authenticator auth = new Authenticator() {
    			public PasswordAuthentication getPasswordAuthentication() {
    				return new PasswordAuthentication("*@*.com", passWord);//""
    			}
    		};
    		Session session = Session.getInstance(props, auth);
    		session.setDebug(true);
    		// 2.创建一个Message,它相当于是邮件内容
    		Message message = new MimeMessage(session);
    		// 设置发送者
    		message.setFrom(new InternetAddress("qq.com"));
    		return message;
    	}
    
    	public static void sendMail(String users, String msg, String title, InputStream is, String passWord) throws AddressException, MessagingException, IOException {
    
    		Message message = initMailInfo(passWord);
    
    		new InternetAddress();
    		InternetAddress[] internetAddressTo = InternetAddress.parse(users);
    
    		// 设置发送方式与接收者多人
    		message.setRecipients(MimeMessage.RecipientType.TO, internetAddressTo);
    		// 设置主题
    		message.setSubject(title);
    		// 6. 创建邮件内容"节点"
    		MimeBodyPart textBodyPart = new MimeBodyPart();
    		textBodyPart.setContent(msg, "text/html;charset=UTF-8");
    
    		// 添加附件节点
    		MimeBodyPart fileBodyPart = new MimeBodyPart();
    		DataSource source = new ByteArrayDataSource(is, "application/msexcel");
    		// 添加附件的内容
    		fileBodyPart.setDataHandler(new DataHandler(source));
    		// 添加附件的标题
    		// 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
    		MimeMultipart multipart = new MimeMultipart();
    	//	fileBodyPart.setFileName(MimeUtility.encodeText(title + ".xls")); 加了这个编码转换 订单反而 有问题  
    // 这个我也不知道为什么 有时候这样 有时候不会 fileBodyPart.setFileName(MimeUtility.encodeText(title + ".xls")); multipart.addBodyPart(fileBodyPart); multipart.addBodyPart(textBodyPart); message.setContent(multipart); // 3.创建 Transport用于将邮件发送 Transport.send(message); } public static void sendMail(String users, String ccAdresses, String msg, String title, InputStream is, String passWord) throws AddressException, MessagingException, IOException { Message message = initMailInfo(passWord); new InternetAddress(); InternetAddress[] internetAddressTo = InternetAddress.parse(users); InternetAddress[] internetAddressCC = InternetAddress.parse(ccAdresses); // 设置发送方式与接收者多人 message.setRecipients(MimeMessage.RecipientType.TO, internetAddressTo); //增加抄送人员 message.setRecipients(MimeMessage.RecipientType.CC, internetAddressCC); // 设置主题 message.setSubject(title); // 6. 创建邮件内容"节点" MimeBodyPart textBodyPart = new MimeBodyPart(); textBodyPart.setContent(msg, "text/html;charset=UTF-8"); // 添加附件节点 MimeBodyPart fileBodyPart = new MimeBodyPart(); DataSource source = new ByteArrayDataSource(is, "application/msexcel"); // 添加附件的内容 fileBodyPart.setDataHandler(new DataHandler(source)); // 添加附件的标题 // 这里很重要,通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码 MimeMultipart multipart = new MimeMultipart(); fileBodyPart.setFileName(MimeUtility.encodeText(title + ".xls")); multipart.addBodyPart(fileBodyPart); multipart.addBodyPart(textBodyPart); message.setContent(multipart); // 3.创建 Transport用于将邮件发送 Transport.send(message); } }

      上面是邮件工具类   下面是调用方法 

     1 /**
     2      * 每天中午一点半 执行 
     3      */
     4     @Scheduled(cron = "0 30 13 ? * *") // 本地注释掉
     5     // @Scheduled(cron = "0 0/1 * * * ?") // 本地注释掉 测试 一分钟执行一次
     6     public void scheduleEvaluationNotice() {
     7 
     8         String serverIP = "";
     9         try {
    10             InetAddress address = InetAddress.getLocalHost();
    11             serverIP = address.getHostAddress();
    12         } catch (UnknownHostException e) {
    13             e.printStackTrace();
    14         }
    15         String code = sysParameterMapper.queryvalue(ConstantsParameter.TIMECONTROLLER_IDENTIFICATION_fACTORY_CODE);
    16         if (serverIP.equals("") ) { // 判断服务器IP
    17 
    18         
    19             try {
    20                 Date date = new Date();
    21                 SimpleDateFormat dateFm = new SimpleDateFormat("E");
    22                 String currSun = dateFm.format(date);
    23 
    24                 int weekday = 0;
    25                 if (currSun.equals("星期一")) {
    26                     weekday = 0;
    27                 } else if (currSun.equals("星期二")) {
    28                     weekday = 1;
    29                 } else if (currSun.equals("星期三")) {
    30                     weekday = 2;
    31                 } else if (currSun.equals("星期四")) {
    32                     weekday = 3;
    33                 } else if (currSun.equals("星期五")) {
    34                     weekday = 4;
    35                 } else if (currSun.equals("星期六")) {
    36                     weekday = 5;
    37                 } else if (currSun.equals("星期日")) {
    38                     weekday = 6;
    39                 }
    40             
    41                 log.info("判断是否发送邮件  " + date + "--" + currSun + "--" + count + "" + " 
    ");
    42                 if (Integer.parseInt(count) == weekday) {
    43                     sendMail();
    44                 }
    45             } catch (Exception e) {
    46                 log.info("发送失败
    ");
    47                 System.out.println(e)
    48 
    49             }
    50         }
    51 
    52     }
    53 
    54     public void sendMail() {
    55         ExcelGenerate excelGenerate = null;
    56         try {
    57             List<Object> export2 = rbbSchedulingService.getExport(new ScheduleEvaluationModel(), "考评", excelGenerate, "Y");
    58             ExcelGenerate export = (ExcelGenerate) export2.get(0);
    59             @SuppressWarnings("unchecked")
    60             List<ScheduleEvaluationModel> list2 = (List<ScheduleEvaluationModel>) export2.get(1);
    61             // 获取输出流
    62             InputStream input = null;
    63 
    64             // 获取输出流
    65             ByteArrayOutputStream bos = new ByteArrayOutputStream();
    66             export.write(bos);
    67             input = new ByteArrayInputStream(bos.toByteArray());
    68 
    69             List<String> mailaddress = mstOrganizationMailMapper.getMailaddress();
    70             if (mailaddress.size() > 0) {
    71                 String users = String.join(",", mailaddress);
    72                 
    73                 MailService.sendMail(users, getTableStart(list2).toString(), "系统自动发送", input, sysParameterMapper.queryvalue(ConstantsParameter.EXMAIL_PASSWORD));
    74                 log.info("发送成功
    ");
    75             }
    76         } catch (Exception e) {
    77             log.info("发送失败
    ");
    78             System.out.println(e);
    79         }
    80 
    81     }
    82 
    83     public StringBuilder getTableStart(List<ScheduleEvaluationModel> list2) {
    84         StringBuilder table = new StringBuilder();
    85         table.append("    <html>");
    86         table.append("     <head>");
    87         table.append("      <title> New Document </title>");
    88         table.append("     </head>");
    89         table.append("     <body>");
    90         table.append("***********略***************");
    91         
    92         table.append("       </table></body></html>  ");
    93         return table;
    94     }

    这两个搭配使用  

  • 相关阅读:
    LOJ#3212. 「CSP-S 2019」划分
    矩阵乘法
    SSF信息社团4月训练题目整理
    AtCoder Regular Contest 116
    SSF信息社团3月训练题目整理
    Codeforces Round #704 (Div. 2)
    SSF信息社团寒假训练题目整理(三)
    关于 zzt 得 0.8 分这件事
    Luogu P7244 章节划分
    SSF信息社团寒假训练题目整理(二)
  • 原文地址:https://www.cnblogs.com/Mr-Y1907/p/14601904.html
Copyright © 2020-2023  润新知