def send_email_report(new_items): from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import (Mail, MimeType, Attachment, FileContent, FileName, FileType, Disposition, ContentId) import base64 email_config = GitHubMonitor.__load_email_config() if not email_config or not new_items: return try: # construct email email = Mail() email.from_email = email_config.sender for recipient in email_config.recipients: email.add_to(recipient) today = time.strftime('%Y-%m-%d', time.localtime()) email.subject = f"[{today}] GitHub Monitoring Report" email.add_content(GitHubMonitor.generate_html_report(new_items), MimeType.html) # send email sendgrid = SendGridAPIClient(email_config.api_key) logger.info(f"Sending email report...") r = sendgrid.send(email) if r.status_code > 400: logger.error(f"SendGrid API failed: error={r.status_code}") except Exception as e: logger.error(f"Failed to send Site SSL Report: {e}")
def send_email(sender, instance, **kwargs): # Get emails of subscribed users sub_emails = User.objects.filter(pk__in=Subscription.objects.filter( publisher__exact=instance.author).values_list( 'subscriber_id')).values_list('email', flat=True) subject = 'New post | Django Boys Blog' text = '<h1>Check new post by ' + instance.author.username + '</h1><a href="/posts/' + str( instance.pk) + '">' + instance.title + '</a>' message = Mail(from_email='*****@*****.**', subject=subject, html_content=text) # Add emails for to_email in sub_emails: message.add_to(to_email) try: sg = SendGridAPIClient(os.environ.get('SENDGRID_API_KEY')) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e.message) pass
def send_message_with_sg(send_to, send_from, subject, body): message = Mail() message.add_to(send_to) message.set_from(send_from) message.set_subject(subject) message.set_html(body) print("Sending email:({}) to :({})".format(subject, send_to)) sg.send(message)
def _send_email_report(self, report): from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import (Mail, MimeType, Attachment, FileContent, FileName, FileType, Disposition, ContentId) import base64 try: email_config = self._email_settings # construct email email = Mail() email.from_email = email_config.sender recipients = email_config.recipients.split(';') for recipient in recipients: email.add_to(recipient) # formatter variables today = time.strftime('%Y-%m-%d', time.localtime()) now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) mapping = {'now': now, 'today': today} email.subject = email_config.subject_formatter.format_map(mapping) email.add_content( self._render_template(email_config.body_template, report), MimeType.html) # get attachment if email_config.include_attachment: content = self._generate_xlsx_report(report) attachment = Attachment() attachment.file_content = base64.b64encode(content).decode() attachment.file_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" attachment.file_name = f"{today}-Site-Report.xlsx" attachment.disposition = "attachment" email.add_attachment(attachment) # send email sendgrid = SendGridAPIClient(email_config.api_key) r = sendgrid.send(email) if r.status_code > 400: logger.error(f"SendGrid API failed: error={r.status_code}") else: logger.info(f"Report was sent successfully.") except Exception as e: logger.error(f"Failed to send Site SSL Report: {e}")
def SendEmails(HubPullRequest, EmailContents, SendMethod): if SendMethod == 'SMTP': # # Send emails to SMTP Server # try: SmtpServer = smtplib.SMTP(SMTP_ADDRESS, SMTP_PORT_NUMBER) SmtpServer.starttls() SmtpServer.ehlo() SmtpServer.login(SMTP_USER_NAME, SMTP_PASSWORD) Index = 0 for Email in EmailContents: Index = Index + 1 EmailMessage = email.message_from_string(Email) print('pr[%d] email[%d]' % (HubPullRequest.number, Index), '----> SMTP Email Start <----') print(Email) print('pr[%d] email[%d]' % (HubPullRequest.number, Index), '----> SMTP Email End <----') if 'From' in EmailMessage: try: FromAddress, FromName = ParseEmailAddress( EmailMessage['From']) except: print('Parsed From: Bad address:', EmailMessage['From']) FromAddress = '*****@*****.**' FromName = 'From %s via TianoCore Webhook' % ( HubPullRequest.user.login) else: print('Parsed From: Missing address:') FromAddress = '*****@*****.**' FromName = 'From %s via TianoCore Webhook' % ( HubPullRequest.user.login) ToList = [] if 'To' in EmailMessage: ToList = ToList + EmailMessage['To'].split(',') if 'Cc' in EmailMessage: ToList = ToList + EmailMessage['Cc'].split(',') try: SmtpServer.sendmail(FromAddress, ToList, Email) print('SMTP send mail success') except: print('ERROR: SMTP send mail failed') SmtpServer.quit() except: print( 'SendEmails: error: can not connect or login or send messages.' ) elif SendMethod == 'SendGrid': # # Send emails to SendGrid # Index = 0 for Email in EmailContents: Index = Index + 1 EmailMessage = email.message_from_string(Email) print('pr[%d] email[%d]' % (HubPullRequest.number, Index), '----> SendGrid Email Start <----') print(Email) print('pr[%d] email[%d]' % (HubPullRequest.number, Index), '----> SendGrid Email End <----') message = Mail() if 'From' in EmailMessage: try: EmailAddress, EmailName = ParseEmailAddress( EmailMessage['From']) message.from_email = From(EmailAddress, EmailName) except: print('Parsed From: Bad address:', EmailMessage['From']) message.from_email = From( '*****@*****.**', 'From %s via TianoCore Webhook' % (HubPullRequest.user.login)) else: print('Parsed From: Missing address:') message.from_email = From( '*****@*****.**', 'From %s via TianoCore Webhook' % (HubPullRequest.user.login)) UniqueAddressList = [] if 'To' in EmailMessage: for Address in EmailMessage['To'].split(','): try: EmailAddress, EmailName = ParseEmailAddress(Address) if EmailAddress.lower() in UniqueAddressList: continue UniqueAddressList.append(EmailAddress.lower()) message.add_to(To(EmailAddress, EmailName)) except: print('Parsed To: Bad address:', Address) continue if 'Cc' in EmailMessage: for Address in EmailMessage['Cc'].split(','): try: EmailAddress, EmailName = ParseEmailAddress(Address) if EmailAddress.lower() in UniqueAddressList: continue UniqueAddressList.append(EmailAddress.lower()) message.add_cc(Cc(EmailAddress, EmailName)) except: print('Parsed Cc: Bad address:', Address) continue message.subject = Subject(EmailMessage['Subject']) for Field in ['Message-Id', 'In-Reply-To']: if Field in EmailMessage: message.header = Header(Field, EmailMessage[Field]) message.content = Content(MimeType.text, EmailMessage.get_payload()) try: sendgrid_client = SendGridAPIClient(SENDGRID_API_KEY) response = sendgrid_client.send(message) print('SendGridAPIClient send success') time.sleep(1) except Exception as e: print('ERROR: SendGridAPIClient failed') else: Index = 0 for Email in EmailContents: Index = Index + 1 EmailMessage = email.message_from_string(Email) print('pr[%d] email[%d]' % (HubPullRequest.number, Index), '----> Draft Email Start <----') if 'From' in EmailMessage: try: EmailAddress, EmailName = ParseEmailAddress( EmailMessage['From']) print('Parsed From:', EmailAddress, EmailName) except: print('Parsed From: Bad address:', EmailMessage['From']) else: print('Parsed From: Missing address:') UniqueAddressList = [] if 'To' in EmailMessage: for Address in EmailMessage['To'].split(','): try: EmailAddress, EmailName = ParseEmailAddress(Address) if EmailAddress.lower() in UniqueAddressList: continue UniqueAddressList.append(EmailAddress.lower()) print('Parsed To:', EmailAddress, EmailName) except: print('Parsed To: Bad address:', Address) continue if 'Cc' in EmailMessage: for Address in EmailMessage['Cc'].split(','): try: EmailAddress, EmailName = ParseEmailAddress(Address) if EmailAddress.lower() in UniqueAddressList: continue UniqueAddressList.append(EmailAddress.lower()) print('Parsed Cc:', EmailAddress, EmailName) except: print('Parsed Cc: Bad address:', Address) continue print('--------------------') print(Email) print('pr[%d] email[%d]' % (HubPullRequest.number, Index), '----> Draft Email End <----')