Java javax.mail 发送邮件,支持ssl,参照springboot的邮件,手动连接服务器

public static String sendMail(ArrayList<String> recivers, String title, String content, int r) {
		try {
			if(email_user.length()<3 || email_pwd.length()<3 || smtp_server.length()<3 || smtp_port.length()<1) {
				CommonUtils.LogError("> email_user+"+email_user+", email_pwd="+email_pwd);
				return "邮件发送者、发送密码等未配置";
			}
			// 创建Properties 类用于记录邮箱的一些属性
	        Properties props = new Properties();
	        // 表示SMTP发送邮件,必须进行身份验证
	        props.put("mail.smtp.auth", "true");
	        
	        //可以不设置下面几个,因为都是手动调用的
	        props.put("mail.smtp.host", smtp_server);
	        props.put("mail.smtp.port", smtp_port);
	        props.put("mail.user", email_user);
	        props.put("mail.password", email_pwd);
	        
	        props.put("mail.smtp.connectiontimeout", smtp_conn_out);
	        props.put("mail.smtp.timeout", smtp_recv_out);
	        props.put("mail.smtp.writetimeout", smtp_send_out);

	        if(smtp_ssl.equals("true")) {
	        	 props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		        props.put("mail.smtp.starttls.enable", smtp_ssl);
		        props.put("mail.smtp.ssl.trust", smtp_server);
	        }

	        for(String key:smtp_settings.keySet()) {
	        	props.put(key, smtp_settings.get(key));
	        }
	        
	        // 构建授权信息,用于进行SMTP进行身份验证
	        Authenticator authenticator = new Authenticator() {	
	            protected PasswordAuthentication getPasswordAuthentication() {
	                // 用户名、密码
	                String userName = props.getProperty("mail.user");
	                String password = props.getProperty("mail.password");
	                return new PasswordAuthentication(userName, password);
	            }
	        };
	        // 使用环境属性和授权信息,创建邮件会话
	        Session mailSession = Session.getInstance(props, authenticator);	        
	        // 创建邮件消息
	        MimeMessage message = new MimeMessage(mailSession);
	        // 设置发件人
	        InternetAddress form = new InternetAddress( props.getProperty("mail.user"));
	        message.setFrom(form);
	
	        // 设置收件人的邮箱
	        for(int i=0;i<recivers.size();i++) {
		        InternetAddress to = new InternetAddress(recivers.get(i));	        
		        message.addRecipient(i==0?RecipientType.TO:RecipientType.CC, to);
	        }
	        // 设置邮件标题
	        message.setSubject(title+", smtp_ssl="+smtp_ssl);
	
	        // 设置邮件的内容体
	        message.setContent(content, "text/html;charset=UTF-8");
	
	        // 最后当然就是发送邮件啦
	        String msg = CommonUtils.getNowDateTimeString()+" > Start send\n";
	        try {
	        	String protocol	= mailSession.getProperty("mail.transport.protocol");
    			if (protocol == null) {
    				protocol = DEFAULT_PROTOCOL;
    			}
    			Transport transport = mailSession.getTransport(protocol);
    			try {
    				transport.connect(smtp_server, CommonUtils.parseInt(smtp_port), email_user, email_pwd);
				} catch (AuthenticationFailedException ex) {
					loge(CommonUtils.getStackTrace(ex));//密码错误不重试					
		        	return "[Fail][Auth]"+ex.getMessage();
				} catch (Exception ex) {
					loge(CommonUtils.getStackTrace(ex));
					if(r<1)
		        		return sendMail(recivers, title, content, r+1);
		        	else
		        		return "[Fail][Connect]"+ex.getMessage();
				}
	        	
    			try {
					if (message.getSentDate() == null) {
						message.setSentDate(new Date());
					}
					String messageId = message.getMessageID();
					message.saveChanges();
					if (messageId != null) {
						message.setHeader(HEADER_MESSAGE_ID, messageId);
					}
					transport.sendMessage(message, message.getAllRecipients());
					transport.close();
				} catch (Exception ex) {
					loge(CommonUtils.getStackTrace(ex));
					if(r<1)
		        		return sendMail(recivers, title, content, r+1);
		        	else
		        		return "[Fail][Send]"+ex.getMessage();
				}
	        	CommonUtils.Log(CommonUtils.getNowDateTimeString()+"【CommonNoticeTool】phones="+CommonUtils.implodeStrArrayList(recivers)+", "+title+" OK\r\n"	, "sms_new_log.txt", true);
	        } catch(Exception e) {
	        	CommonUtils.Log(msg+CommonUtils.getNowDateTimeString()+":"+CommonUtils.getStackTrace(e)+",retry="+r+", "+title+", "+content+", "+"\n", "emails.log", true);
	        	return "[Fail]"+e.getMessage();
	        }
	        return "[OK]";
		}catch(Exception e) {
			log2(CommonUtils.getStackTrace(e));
			return "[Fail]"+e.getMessage();
		}
	}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值