global class InventorySendMailBatch implements Database.Batchable , Database.Stateful{ private boolean result; private string Errorstr; private string logstr; global InventorySendMailBatch() { this.result = true; this.Errorstr = ''; this.logstr = ''; } global Database.QueryLocator start(Database.BatchableContext BC) { return Database.getQueryLocator( [SELECT (select userOrGroupId from groupMembers) FROM group WHERE name = '样本盘点小组'] ); } global void execute(Database.BatchableContext BC, List gList) { List IdList = new List(); if (gList != null && gList.size() > 0) { for (Group g : gList) { for (GroupMember gm : g.groupMembers) { IdList.add(gm.userOrGroupId); } } } Date toDate = Date.today(); Integer day = Integer.valueOf(toDate.day()); if(System.Test.isRunningTest() || (IdList.size() > 0 && (day == 10 || day == 14))){ sendMail(IdList); } } global void finish(Database.BatchableContext BC) { saveResult(); } public void saveResult() { BatchIF_Log__c iflog = new BatchIF_Log__c(); iflog.Type__c = 'PushNotification'; iflog.Log__c = 'InventorySendMailBatch start' + '\n'; if (result) { iflog.Is_Error__c = 0; iflog.ErrorLog__c = ''; if (logstr.length() > 65000) { logstr = logstr.substring(0, 65000); logstr += ' ...have more lines...'; } iflog.Log__c += '邮件成功发送\n end'; } else { iflog.Is_Error__c = 1; if (Errorstr.length() > 65000) { Errorstr = Errorstr.substring(0, 65000); Errorstr += ' ...have more lines...'; } if (logstr.length() > 65000) { logstr = logstr.substring(0, 65000); logstr += ' ...have more lines...'; } iflog.Log__c += logstr; iflog.ErrorLog__c = Errorstr; } insert iflog; } public boolean sendMail(List IdList) { boolean rs = true; List userList = [select Id, Name, Email, Manager.Email from User where id IN :IdList]; List sendMails = new List(); for(User user : userList){ String title = ''; String body = ''; title = '【提醒】' + '办事处样本盘点工作的开展'; body += user.Name + '您好:'; body += '
'; body += '
'; body += '本月的样本盘点工作已经开始,请您及时进行样本盘点。
'; body += '若本月已经进行过样本盘点,还请忽略本邮件。
'; body += '
'; body += '
'; body += '谢谢!'; //收件邮箱 List toMailList = new List(); toMailList.add(user.Email); //抄送的邮箱 List ccMailList = new List(); if(user.Manager.Email != null){ ccMailList.add(user.Manager.Email); } Messaging.SingleEmailMessage messageNEW = new Messaging.SingleEmailMessage(); messageNEW.subject = title; messageNEW.htmlBody = body; messageNEW.setCharset('UTF-8'); messageNEW.toAddresses = toMailList; if(ccMailList.size() > 0){ messageNEW.ccAddresses = ccMailList; } sendMails.add(messageNEW); } //在单个事务中,只能调用send方法 10 次。 Messaging.SendEmailResult[] results = messaging.sendEmail(sendMails); for (Integer i = 0; i < results.size(); i++) { if (results[i].success == false) { system.debug('=====send mail error:' + results[i].errors[0].message); result = false; Errorstr += 'sendMail error:' + results[i].errors[0].message + '\n'; rs = false; } } return rs; } }