def compose_email(account, subject, body, recipient, attachment_file_path): """ Create html email and attach file""" msg = Message(account=account, folder=account.sent, subject=subject, body=HTMLBody(body), to_recipients=[Mailbox(email_address=recipient)]) fn = os.path.basename(attachment_file_path) with open(attachment_file_path, 'rb') as f: attch_file = FileAttachment(name=fn, content=f.read()) msg.attach(attch_file) return msg
def send_email_to_mailbox(account: Account, to: List[str], subject: str, body: str, bcc: List[str], cc: List[str], reply_to: List[str], html_body: Optional[str] = None, attachments: Optional[List[str]] = None, raw_message: Optional[str] = None, from_address: Optional[str] = None): """ Send an email to a mailbox. Args: account (Account): account from which to send an email. to (list[str]): a list of emails to send an email. subject (str): subject of the mail. body (str): body of the email. reply_to (list[str]): list of emails of which to reply to from the sent email. bcc (list[str]): list of email addresses for the 'bcc' field. cc (list[str]): list of email addresses for the 'cc' field. html_body (str): HTML formatted content (body) of the email to be sent. This argument overrides the "body" argument. attachments (list[str]): list of names of attachments to send. raw_message (str): Raw email message from MimeContent type. from_address (str): the email address from which to reply. """ if not attachments: attachments = [] message_body = HTMLBody(html_body) if html_body else body m = Message( account=account, mime_content=raw_message.encode('UTF-8') if raw_message else None, folder=account.sent, cc_recipients=cc, bcc_recipients=bcc, subject=subject, body=message_body, to_recipients=to, reply_to=reply_to, author=from_address) if account.protocol.version.build <= EXCHANGE_2010_SP2: m.save() for attachment in attachments: m.attach(attachment) m.send() else: for attachment in attachments: m.attach(attachment) m.send_and_save() return m
def _send_email( self, account, subject, body, recipients, attachments: [Attachment] = None, reply_to: [str] = [], ): """ Send an email. Parameters ---------- account : Account object subject : str body : str recipients : list of str Each str is and email adress attachments : list of tuples or None (filename, binary contents) Examples -------- >>> send_email(account, 'Subject line', 'Hello!', ['*****@*****.**']) """ to_recipients = [] for recipient in recipients: to_recipients.append(Mailbox(email_address=recipient)) reply_to_addresses = [] for address in reply_to: reply_to_addresses.append(Mailbox(email_address=address)) m = Message( account=account, folder=account.sent, subject=subject, body=HTMLBody(body), to_recipients=to_recipients, reply_to=reply_to, ) # attach files for attachment in attachments or []: file = FileAttachment(name=attachment.file_name, content=attachment.content) m.attach(file) logging.info("Sending mail to {}".format(to_recipients)) m.send_and_save()
def create_email_message(self, username, subject, body, to_recipients): """Create an email message object""" account = self.connect_to_account( username, impersonation=(username != self.email)) html_body = HTMLBody('<html><body>{}</body></html>').format(body) email = Message(account=account, folder=account.sent, subject=subject, body=html_body, to_recipients=[ recipient.strip() for recipient in to_recipients.split(',') ]) return email
def send_phishing_email(self, link_replace=True, link='https://www.basspro.com', attach_file=False, file_path='', file_name='Resume'): """Send phishing emails from a compromised account. :param link_replace: (Boolean) if you want to replace the links in the email or not :param link: (String) if you do want to link replace, this is the link that will replace all of the existing links :param attatch_file: (Boolean) if you want to attach a file or not :param file_path: (String) if you want to attach a file, the path of the desired file :param file_name: (String) if you want to attach a file, the name that you want the reciever to see """ # Find the correct folder in the red_account old_emails = [] for folder in self._red_account.inbox.children: if folder.name == self.full_username: for sub_folder in folder.children: if sub_folder.name == "to_send": old_emails = [email for email in sub_folder.all()] break break # Iterate through emails and either replace links or attach files new_emails = [] for email in old_emails: m = Message(account=self._victim_account, subject=email.subject, body=email.body, to_recipients=email.to_recipients) # Replace links if link_replace: replace_string = 'href="' + link + '"' m.body = HTMLBody(re.sub(r'href="\S*"', replace_string, m.body)) # Attach file if attach_file: m = self.attach_file(m, file_path, file_name) new_emails.append(m) print("Sending emails from the victim... ") self.vic_send_emails(new_emails)
def Email(to, subject, body): creds = Credentials(username=sender, password=password) account = Account(primary_smtp_address='*****@*****.**', credentials=creds, autodiscover=True, access_type=DELEGATE) m = Message(account=account, subject=subject, body=HTMLBody(body), to_recipients=[Mailbox(email_address=to)]) try: m.send() print("send ok") except Exception as e: print(e)
def send_email(self, to_address, subject, body, cc_recipients=[]): """ Send a trial or pending email based on the club """ # Build and send message msg = Message( account=self.account, folder=self.account.sent, subject=subject, body= HTMLBody(body), to_recipients=[Mailbox(email_address=to_address)], cc_recipients=[(Mailbox(email_address=x)) for x in cc_recipients] ) msg.send_and_save() print("Message to {} sent.".format(to_address))
def sendEmail(to, subject, body): BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter creds = Credentials(username='******', password='******') config = Configuration(server='rndcas.h3c.com', credentials=creds, auth_type=NTLM) account = Account(primary_smtp_address=SENDER, config=config, autodiscover=False, access_type=DELEGATE) m = Message(account=account, subject=subject, body=HTMLBody(body), to_recipients=[Mailbox(email_address=to)]) m.send_and_save()
def sendmail(self,filename): # 此句用来消除ssl证书错误,exchange使用自签证书需加上 BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter cred = Credentials(self.EmailUser, self.Password) mailconfig = Configuration( server=self.EmailServer, credentials=cred, auth_type=NTLM) account = Account( primary_smtp_address=self.sender, config=mailconfig, autodiscover=False, access_type=DELEGATE) sleep(1) #打开测试报告,读取报告内容 try: with open(os.path.join(reportPath,filename),'rb') as f: fileMsg = f.read().decode('utf-8') except Exception as e: log1.exception('open or read file [%s] failed,No such file or directory: %s' %(filename, reportPath)) raise e else: log1.info('open and read file [%s] successed!' % filename) #登录服务器,连接邮箱,设置邮件 try: m = Message( account=account, subject="测试邮件", # 邮件主题 body=HTMLBody(fileMsg), to_recipients=self.addresser ) except Exception: log1.exception('connect [%s] server failed or username and password incorrect!' %self.EmailServer) else: log1.info('connect [%s] server successed !' %self.EmailServer) #发送邮件 try: m.send() except Exception: log1.exception('send mail failed !') else: log1.info('send mail successed !')
def ews_read_folder(ews_account, subfolder=''): ''' EWS Account Obj -> Python List of HTML Email bodies ''' try: location = ews_account.inbox if subfolder != '': location = ews_account.inbox / subfolder folder = location.all().order_by('-datetime_received') output = list() for email in folder: output.append(str(HTMLBody(email.body))) return output except Exception as error_text: print(f'[Error] Unable to read email folder - {str(error_text)}') sys.exit()
def Email(to, subject, body): creds = Credentials( username='******', password='******' ) account = Account( primary_smtp_address='*****@*****.**', credentials=creds, autodiscover=True, access_type=DELEGATE ) m = Message( account=account, subject=subject, body=HTMLBody(body), to_recipients=[Mailbox(email_address=to)] ) m.send()
def Email(to, subject, body): creds = Credentials( username='******', password='******' ) account = Account( primary_smtp_address='*****@*****.**', credentials=creds, autodiscover=True, access_type=DELEGATE ) m = Message( account=account, subject=subject, body=HTMLBody(body), to_recipients = [Mailbox(email_address=to)] ) m.send()
def send_email( self, to: Union[str, List[str]], header: str, body: str, attachments: dict ): """ This method sends an email from the login address (attribute login_address). Parameters ---------- to: str or list Address or list of addresses of email recipients header: str Email header body: str Email body attachments: dict Dict containing attachment names as key and attachment file contents as values. Currently, the code is tested for DataFrame attachments only. """ if self.sender_account is None: raise AttributeError( "To send emails, you need to specify a `sender_address` when initializing " "the ExchangeConnector class." ) if isinstance(to, str): to = [to] # Prepare Message object m = Message( account=self.sender_account, subject=header, body=HTMLBody(body), to_recipients=to, ) if attachments: for key, value in attachments.items(): m.attach(FileAttachment(name=key, content=bytes(value, "utf-8"))) # Send email m.send() logger.info(f"Email sent from address '{self.sender_address}'")
def email(report_path, attachment): html_report_path = os.path.join(report_path, attachment) content = open(html_report_path, 'rb').read() credentials = Credentials('*****@*****.**', 'Jt123456') account = Account('*****@*****.**', credentials=credentials, autodiscover=True) item = Message( account=account, subject="{} Automation Report".format(datetime.datetime.now().strftime('%Y-%m-%d-%H')), body=HTMLBody('This is an automation run result report email. Please do not reply.*'), to_recipients=[ Mailbox(email_address='*****@*****.**'), Mailbox(email_address='*****@*****.**'), Mailbox(email_address='*****@*****.**'), ], ) my_file = FileAttachment(name=attachment, content=content) item.attach(my_file) item.send()
def EmailWarning(subject, body): creds = Credentials( # 域账号和密码 username='******', password='******') account = Account( # 发送邮件的邮箱 primary_smtp_address='@.com', credentials=creds, autodiscover=True, access_type=DELEGATE) m = Message(account=account, subject=subject, body=HTMLBody(body), to_recipients=[ Mailbox(email_address='@.com'), Mailbox(email_address='@.com'), Mailbox(email_address='@.com'), Mailbox(email_address='@.com'), Mailbox(email_address='@.com'), ] # 向指定邮箱里发预警邮件 ) m.send()
def process_message(self, peer, mailfrom, rcpttos, data, **kwargs): print('Receiving message from:', peer) print('Message addressed from:', mailfrom) print('Message addressed to :', rcpttos) print('Message length :', len(data)) self._save_message(data) msg = email.message_from_bytes(data) if msg.is_multipart(): print("multipart mail, ignored!") else: subject = decode_mime_words(msg.get('subject', '')) body = msg.get_payload(decode=True).decode('utf8') charset = msg.get_content_charset() content_encoding = msg.get('content-transfer-encoding', '') content_type = msg.get_content_type() print('Message subject :', subject) print("orig subject=", msg.get('subject', '')) print('Message charset :', charset) print('Message encoding :', content_encoding) print('Message type :', content_type) # now to EWS ... if is_probably_html(body, content_type): body = HTMLBody(body) recipients = [Mailbox(email_address=r) for r in rcpttos] m = Message( account=self.account, folder=self.account.sent, subject=subject, body=body, to_recipients=recipients ) m.send_and_save() print("mail sent via Exchange")
def send_email_to_mailbox(account, to, subject, body, bcc=None, cc=None, reply_to=None, html_body=None, attachments=[]): message_body = HTMLBody(html_body) if html_body else body m = Message( account=account, folder=account.sent, cc_recipients=cc, bcc_recipients=bcc, subject=subject, body=message_body, to_recipients=to, reply_to=reply_to ) if account.protocol.version.build <= EXCHANGE_2010_SP2: m.save() for attachment in attachments: m.attach(attachment) m.send() else: for attachment in attachments: m.attach(attachment) m.send_and_save() return m
def sendmail(self, subject, body, filename, receiver): creds = Credentials(username=self.username, password=self.password) account = Account(primary_smtp_address=self.username, credentials=creds, autodiscover=True, access_type=DELEGATE) to_recipients = [] for to in receiver: to_recipients.append(Mailbox(email_address=to)) m = Message( account=account, subject=subject, body=HTMLBody(body), to_recipients=to_recipients, ) file = FileAttachment(name='Test_report.html', content=open(filename, 'rb').read()) m.attach(file) m.send()
def mail_send(name_user, mail_address): mail_address = mail_address.replace("['", "") mail_address = mail_address.replace("']", "") data = mail_body(name_user) mail_Data = data[0] is_send = int(data[1]) if is_send == 0: file = name_user.replace(".xls", "") now = datetime.datetime.now() the_time = now.strftime('%Y' + "年" + '%m' + "月" + '%d' + "日") m = Message(account=account, subject=the_time + file + "现存漏洞清单", body=HTMLBody(mail_Data), to_recipients=[Mailbox(email_address=mail_address)], cc_recipients=["**********", "**********"]) with open(name_user, "rb") as f: conf = f.read() attch = FileAttachment(name=name_user, content=conf) m.attach(attch) m.send_and_save() else: pass return
def send_msg(body): requests.urllib3.disable_warnings() ssl._create_default_https_context = ssl._create_unverified_context from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter sender = '@.com' user = '******' import sys mail_pass = sys.argv[1] print user, mail_pass credentials = Credentials( username=user, # Or [email protected] for O365 password=mail_pass) mail_host = ".." config = Configuration(credentials, server=mail_host) account = Account(primary_smtp_address=sender, config=config, access_type='delegate') addr = "@.com" subject = u"" m = Message( account=account, subject=subject, body=HTMLBody("".join(body)), to_recipients=[ Mailbox(email_address=addr), ], ) m.send() logger.info("Sended subject: %s to %s", subject, addr)
def email(report_path, attachment, setting_name='default'): def get_receiver(mailbox_list): list_receiver = [] for mailbox in mailbox_list.split(','): list_receiver.append(Mailbox(email_address=mailbox.strip(' '))) return list_receiver config_file_path = os.path.join(COMMON_CONFIG_DIR, 'mail_config.yaml') settings = Yaml(config_file_path).read_get(setting_name) sender = settings['sender'] pwd = settings['password'] subject = settings['subject'] list_to = get_receiver(settings['to']) list_cc = get_receiver(settings['cc']) html_report_path = os.path.join(report_path, attachment) content = open(html_report_path, 'rb').read() credentials = Credentials(sender, pwd) account = Account(sender, credentials=credentials, autodiscover=True) item = Message( account=account, subject="{} {}".format(datetime.datetime.now().strftime('%Y-%m-%d-%H'), subject), #body=HTMLBody(content.decode('utf-8')), body=HTMLBody( 'This is an automation run result report email. Please do not reply.*' ), to_recipients=list_to, cc_recipients=list_cc, ) my_file = FileAttachment(name=attachment, content=content) item.attach(my_file) item.send()
def send(recipients, invoice_ref): """Construct email from Recipient object and send. Args: recipients (list): A list of recipient objects invoice_ref (str): Identifier of the invoice being emailed """ for recipient in recipients: address = recipient.heademail cc_address = recipient.admemail if recipient.send_only_admin: address = recipient.admemail cc_address = "" print("address: {}".format(address)) print("cc_address: {}".format(cc_address)) try: m = Message(account=account, folder=account.sent, subject=('NIC@KCL: Invoice {0}'.format(invoice_ref)), to_recipients=[Mailbox(email_address=address)]) if cc_address: m.cc_recipients = [ Mailbox(email_address=cc_address), ] f = open(recipient.invoice, "r").read() m.body = HTMLBody(f) m.send_and_save() except: print('could not send email about {}'.format(invoice_ref)) pass
This material is produced in connection with, and for the purpose of the Patient Safety Evaluation System and-or Review Organization established at the University of New Mexico Hospital, and is therefore confidential Patient Safety Work Product (“PSWP”) and/or confidential peer review material of the University of New Mexico Hospital as defined in 42 C.F.R. subsection 3.20 and-or the Review Organizations Immunity Act, Section 41-9-1 et seq., NMSA 1978 as amended (ROIA). As such, it is confidential and is protected under federal law 42 C.F.R. subsection3.206 and/or ROIA. Unauthorized disclosure of this document, enclosures thereto, and information therefrom is strictly prohibited. </font> </head> <html> ''' #add the parts of the mail message html = greeting + unit_table + disclaimer m = Message( account=a, subject='FYI - Possible COVID-19 Risk *Secure*', body= HTMLBody(html), to_recipients=[ Mailbox(email_address= email), # will be email variable ], cc_recipients=['*****@*****.**'], # Simple strings work, too bcc_recipients=[], # Or a mix of both ) ################################################################# # to implement this in production, change .Display to .Send ################################################################# m.send() ################################################################################################################################################## ##delete the original file to prevent re-running the script on an outdated file if the process to drop the file in a folder errors os.remove(data_path / file_name) ################################################################################################################################################## print(str(timestr) + ' COVID-19 Risk Emails Sent')
def sendMail(user, mailType = 'Debt', debtLimit = 0): # 'Pwd' mail if mailType == 'Pwd': # We generate a random password and find the SHA256 hash newPwd = genNewPwd() newPwdHash = sha256(newPwd.encode()).hexdigest() # The mail text for a 'Pwd' mail is loaded and converted to HTML path = dataFolder + 'newPwdMail.t' with open(path, 'r', encoding='utf-8') as mailFile: messageText = plainToHtml(mailFile.read()) # Next the user specific information is substituted in the mail # Valid substitutes are (so far): {name}, {sduId} and {pwd} subList = [('{name}', user.name), ('{sduId}', user.sduId), ('{pwd}', newPwd)] for key, subst in subList: messageText = messageText.replace(key, subst) # A connection is made to the Exchange server account = loginExchange() # And a message is created message = Message(account = account, folder = account.sent, subject = 'Nyt password til Æters Ølliste', body = HTMLBody(messageText), to_recipients = [Mailbox(email_address = user.mail)]) try: # We then try sending the message, and if it succeds the users pwd is overwritten # and the user is saved. message.send_and_save() user.pwd = newPwdHash user.saveUser() sent = True except: # If sending it fails a flag is set to False sent = False # The connection is closed and the flag is returned account.protocol.close() return sent # 'Debt' mails elif mailType == 'Debt': # As 'Debt' means that 'user' is actually a list and for ease of reading it is renamed to reflect that users = user # The list of tuples to be returned usersStatus = [] # Next the template text of the 'Debt' mail is loaded and (roughly) converted to HTML path = dataFolder + 'debtMail.t' with open(path, 'r', encoding='utf-8') as mailFile: templateText = plainToHtml(mailFile.read()) # The URL any (non-mobile) webbrowser will show when the embedded hyperlink is pressed altUrl = 'https://www.facebook.com/aeter.sdu/' # Any embedded URL should be referenced in the template as '{url}Text here{/url}' where # the middle text will be the text of the hyperlink. # Please note that though this script (as of now) supports multiple URL in the same text, # the destination will always be the same. # # Any embedded URLs in the template are identified and listed urlTexts = [] startIndex = 0 while True: tmpIndex = templateText[startIndex:].find('{url}') + startIndex + 5 if tmpIndex - startIndex != 4: startIndex = tmpIndex endIndex = templateText[startIndex:].find('{/url}') + startIndex urlTexts.append(templateText[startIndex:endIndex]) else: break # A connection to the Exchange server is created account = loginExchange() # Looping over all users for user in users: # Checking if the user balance is indeed above the debtLimit if user.balance > debtLimit: # A custom QR code and MobilePay URL are generated qrCodePath, mobilePayUrl = generateQR(user, extraAmount = 0, returnUrl = True) # A "dict" over the proper (AppRedirect) URLs is created from the custom MP URLs urlSubs = htmlUrls(urlTexts, altUrl, mobilePayUrl) # Next the user specific information is substituted in the template # Valid substitutes are (so far): {name}, {balance}, {sduId}, {qrcode}, {FacebookUrl} and {url}TEXT HERE{/url} subList = [('{name}', user.name), ('{balance}', str(user.balance)), ('{sduId}', user.sduId), ('{FacebookUrl}', '<a href=https://www.facebook.com/aeter.sdu/>Facebook</a>'), ('{qrcode}', f'<img src="cid:{qrCodePath[-10:-4]}">')] + urlSubs messageText = templateText for key, subst in subList: messageText = messageText.replace(key, subst) # Next the newly created QR code is loaded into a file attachment with open(qrCodePath, 'rb') as qrFile: qrImage = FileAttachment(name = qrCodePath[-10:-4], content = qrFile.read()) # The message is set up and the qr code attached message = Message(account = account, folder = account.sent, subject = 'Opgørelse af Æters Ølliste', body = HTMLBody(messageText), to_recipients = [Mailbox(email_address = user.mail)]) message.attach(qrImage) try: # The message is then sent and the user/True tuple is added to the out list if succesfull message.send_and_save() usersStatus.append((user, True)) except: # If the message is not sent, the user/False tuple is added instead usersStatus.append((user, False)) else: # If the user has a balance below the debtLimit, the user/False tuple is added to the out list. # (They can be differentiated from failed attempts at sending later on.) usersStatus.append((user, False)) # In the end, the connection is closed and the tuples list is returned account.protocol.close() return usersStatus # 'ManBalance' mails elif mailType == 'ManBalance': # The content of the manual balance mail is created on spot plainText = f""" Hi Cashier, A user named {user.name.split()[0]} has just been created with a manual balance input of {user.balance}. Further user properties are: Name: {user.name} Sdu-Id: {user.sduId} Mail: {user.mail} User no.: {user.number} Balance: {user.balance} Best regards, The Beerlist """[1:].replace(' ','') # And it is then converted to HTML messageText = plainToHtml(plainText) # A connection is made to the Exchange server account, mail = loginExchange(returnSender=True) # And a message is created message = Message(account = account, folder = account.sent, subject = 'Nyt password til Æters Ølliste', body = HTMLBody(messageText), to_recipients = [Mailbox(email_address = mail)]) try: # We then try sending the message message.send_and_save() sent = True except: # If sending it fails a flag is set to False sent = False # The connection is closed and the flag is returned account.protocol.close() return sent elif mailType == 'Debug': print('Opened function') # The content of the debugging mail is created on spot plainText = f""" Hi, Good luck with the debugging! below you can find properties of the specified user. Further user properties are: Name: {user.name} Sdu-Id: {user.sduId} Mail: {user.mail} User no.: {user.number} Balance: {user.balance} Best regards, The Beerlist """[1:].replace(' ', '') # And it is then converted to HTML messageText = plainToHtml(plainText) print('Text converted to HTML') # A connection is made to the Exchange server account = loginExchange() print('Started exchange session') # And a message is created message = Message(account=account, folder=account.sent, subject='Debugging mail fra Æters ølliste', body=HTMLBody(messageText), to_recipients=[Mailbox(email_address= user.mail)]) print('Defined message body') try: # We then try sending the message message.send_and_save() sent = True print('Finished trying') except: # If sending it fails a flag is set to False sent = False print('Finished expception') # The connection is closed and the flag is returned print('Closing protocol') account.protocol.close() print('Protocol closed') return sent
html += f'<td>{" "}</td>' html += "</tr>" html += """ </table> <p> <br> With Regards<br> Pankaj Barnwal<br> </p> </body> </html> """ # print(html) return html wb = create_mail_table(wb) msg = Message(account=account, subject="eRACTS complaint status - Sambalpur DO", body=HTMLBody(create_html(wb)), to_recipients=['*****@*****.**']) msg.send_and_save() """ with open("Simple.html", "w", encoding="utf-8") as filehtml: filehtml.write(html) os.system("Simple.html") """
###################### ##Send Email import sys sys.path.append('C:\ProgramData\Anaconda3\Lib\site-packages') from exchangelib import Configuration, Account, DELEGATE #ServiceAccount, from exchangelib import Message, Mailbox, FileAttachment,ItemAttachment from config import cfg # load your credentials subject = 'Testing via Exchangelib in Python' --body = 'This is an autogenerated mail.Please do not respond.' body = HTMLBody('<html><body><b>This is an autogenerated mail.</b>Please do not respond.</body></html>') recipients = ['***'] def send_email(account, subject, body, recipients, attachments): to_recipients = [] for recipient in recipients: to_recipients.append(Mailbox(email_address=recipient)) # Create message m = Message(account=account, folder=account.sent, subject=subject, body=body, to_recipients=to_recipients) # attach files #for attachment_name, attachment_content in attachments or []:
# getting the sensitive information from enviornment variables # stored in the .bash_profile outlook_user = os.environ.get('OUTLOOK_USER') outlook_password = os.environ.get('OUTLOOK_PASS') outlook_server = os.environ.get('OUTLOOK_SERVER') outlook_email = os.environ.get('OUTLOOK_EMAIL') # Using the necessary credential and configuration to connect to # the exchange server credentials = Credentials(username=outlook_user, password=outlook_password) config = Configuration(server=outlook_server, credentials=credentials) account = Account(primary_smtp_address=outlook_email, config=config, autodiscover=False, access_type=DELEGATE) msg = Message( account=account, subject="HTML formatted mail", body=HTMLBody( """ <html> <body> <h1>Hey! straight from the HTML</h1 </body </html> """), to_recipients=['*****@*****.**'] ) msg.send_and_save()
def EmailChecker_WARN(folder,tag,curdir): # Get the folder - Lines for testing # tag = "[DETECTION] " # # folder = a.inbox // "DMAS Alerts" # Assign Blank Detection statistics dictionary DetectStats = {"Origin Time" : "", "Issue Time" : "", "Correlator Issuer" : "", "Epicenter" : "", "Magnitude" : ""} # Empty dictionary for epicenter detected stations StatLocals = {} # Sort the emails in the folder from newest to oldest and grabs the most # recent detection warning for item in folder.all().order_by('-datetime_received')[:1]: data = [] soup = BeautifulSoup(item.body,'lxml') # Extracts email body/HTML text parse = soup.text.split("\n") # Extracts the body text # Get the detection stats for the new email DetectStats["Origin Time"] = parse[parse.index("OriginTime") + 1] DetectStats["Issue Time"] = parse[3] DetectStats["Correlator Issuer"] = parse[2] DetectStats["Epicenter"] = parse[parse.index("Epicentre") + 1] DetectStats["Magnitude"] = parse[parse.index("Magnitude") + 1] # Reformat times origin = datetime.strptime(DetectStats['Origin Time'], '%Y-%m-%dT%H:%M:%S+00:00') pst_origin = origin - timedelta(hours = 8) issue = datetime.strptime(DetectStats['Issue Time'], '%Y-%m-%dT%H:%M:%S+00:00') pst_issue = issue - timedelta(hours = 8) # False Check # Noticed if there is a false alarm, the difference between the issue time and # origin time is around 4 mins. Added check to ensure these times are < 2mins. t = issue - origin detectType = True if t > timedelta(seconds = 120): tag = "[DETECTION - POTENTIAL FALSE] " fail = "FALSE DETECTION SUSPECTED! Difference between Origin and Issue times = " + str(t) detectType = False dfrom = datetime.strftime(origin, '%Y-%m-%dT%H:%M:%S.000Z') dto = datetime.strftime(origin + timedelta(minutes = 1), '%Y-%m-%dT%H:%M:%S.000Z') # Grab the most recent event from the detection list that is associated with the email url='https://data.oceannetworks.ca/EventDefinitionService?operation=12&eventDefinitionId=17&sort=timestamp&dir=desc&startIndex=0&results=60' response = requests.get(url) data = response.json() # Unpack the HTML payloadNow = data['payload']['records'][0]['payload'] # Get the list of stations that was in the payload of the event list stFrnt = payloadNow[(payloadNow.find('Sensors=[')+9):] stsens = stFrnt[:stFrnt.find(']')] # stsens = "24313, 23466, 24063, 30479, 23463, 24317, 24316, 24315, 24069, 24324" # Maps the stations to a list stationList = list(map(int, re.findall(r'\d+',stsens))) # Gets the station information for the dictionary for stat in stationList: filters = {'deviceId': str(stat)} try: result = onc.getLocations({'deviceCode': (onc.getDevices(filters))[0]['deviceCode'], 'dateFrom' : dfrom, 'dateTo' : dto}) detect = {stat : {"lat" : result[0]['lat'], "lon" : result[0]['lon'], "name": result[0]['locationCode']}} StatLocals.update(detect) except: continue # Gets the event epicenter lat, lon = DetectStats['Epicenter'].split(',') lat = float(lat) lon = float(lon) # Plots the base image onto the figure plt.figure(figsize = (9, 6)) fname = curdir + '/_Maps/EEW_Base.png' img_extent = (-131.75, -123, 46, 52.2) img = plt.imread(fname) ax = plt.axes(projection = ccrs.Mercator()) origin = datetime.strptime(DetectStats['Origin Time'], '%Y-%m-%dT%H:%M:%S+00:00') pst_origin = origin - timedelta(hours = 8) issue = datetime.strptime(DetectStats['Issue Time'], '%Y-%m-%dT%H:%M:%S+00:00') pst_issue = issue - timedelta(hours = 8) plt.title("Earthquake Occurred at: " + pst_origin.strftime('%Y-%m-%d, %H:%M:%S') + "(PST)\nMagnitude (M): " + DetectStats['Magnitude'] + ". Epicenter = " + DetectStats['Epicenter']) # set a margin around the data ax.set_xmargin(0.05) ax.set_ymargin(0.10) # add the base image ax.imshow(img, origin = 'upper', extent = img_extent, transform = ccrs.Mercator()) ax.coastlines(resolution='10m', color='black', linewidth=1) # Plot the epicenter ax.plot(lon, lat, 'k*', markersize=12, transform=ccrs.Mercator(), label = "Epicenter") ax.annotate("M"+ DetectStats['Magnitude'], (lon + 0.1, lat)) # Creates list of the detection stations for the email statDetect = "Detection Stations: " # mark detectionstations for key in range(len(stationList)): if key == 0: try: ax.plot(StatLocals[stationList[key]]['lon'], StatLocals[stationList[key]]['lat'], 'r^', markersize=8, label = "Epicenter Detection Station", transform=ccrs.Mercator()) ax.annotate(StatLocals[stationList[key]]['name'], (StatLocals[stationList[key]]['lon'], StatLocals[stationList[key]]['lat'])) statDetect += StatLocals[stationList[key]]['name'] + " (" + str(stationList[key]) + ")" except: statDetect += "PNSN Station " + str(stationList[key]) else: try: ax.plot(StatLocals[stationList[key]]['lon'], StatLocals[stationList[key]]['lat'], 'r^', markersize=8, transform=ccrs.Mercator()) ax.annotate(StatLocals[stationList[key]]['name'], (StatLocals[stationList[key]]['lon'], StatLocals[stationList[key]]['lat'])) statDetect += ", " + StatLocals[stationList[key]]['name'] + " (" +str(stationList[key]) + ")" except: statDetect += ", PNSN Station " + str(stationList[key]) ax.legend() location = curdir + '/_Maps/' + 'Map' + issue.date().strftime('%Y-%m-%d') + '.png' # Save the figure plt.savefig(location) # Grab the saved image for the email with open(location, "rb") as fp: map_attach = FileAttachment(name = location, content = fp.read()) # Create strings for HTML body text cor_iss = "Correlator Issuer: " + DetectStats['Correlator Issuer'] mag_epi = "Magnitude: M" + DetectStats['Magnitude'] + ". Epicenter: " + DetectStats['Epicenter'] iss_time = "Issue Time: "+ issue.strftime('%Y-%m-%d, %H:%M:%S') + " (UTC). " + pst_issue.strftime('%Y-%m-%d, %H:%M:%S') + " (PST)" or_time = "Origin Time: "+ origin.strftime('%Y-%m-%d, %H:%M:%S') + " (UTC). " + pst_origin.strftime('%Y-%m-%d, %H:%M:%S') + " (PST)" # Constructs the response email body if detectType == True: tit = HTMLBody('<html><body><p>' + iss_time + '</p><p>' + or_time + '</p><p>' + mag_epi + '</p><p>' + cor_iss + '</p><p>' + statDetect + '</body></html>') else: tit = HTMLBody('<html><body><p>' + fail + '</p><p>' + iss_time + '</p><p>' + or_time + '</p><p>' + mag_epi + '</p><p>' + cor_iss + '</p><p>' + statDetect + '</body></html>') # Composes change email to return (can go to any email) m = Message( account=a, subject = tag + " M" + DetectStats['Magnitude'] + " Earthquake Warning Issued: " + pst_issue.strftime('%Y-%m-%d, %H:%M:%S') + " (PST)", body = tit, to_recipients = [Mailbox(email_address='email(s)toRecieveWarning')] ) m.attach(map_attach) # Send away! m.send()
def EmailChecker(folder,tag): # Assign blank variables data_old = [] data_new = [] date_new = [] date_old = [] loop = 0 # Check if the new email is the first for the folder if folder.total_count > 1: t = 2 elif folder.total_count <= 1: t = 1 # Sort the emails in the folder from newest to oldest and grab the 2 # most recent emails. for item in folder.all().order_by('-datetime_received')[:t]: data = [] soup = BeautifulSoup(item.body,'lxml') # Extracts email body/HTML text table = soup.table # Finds the table contained in the body trows = table.find_all('tr') # Reconstructs the table headerow = [td.get_text(strip=True) for td in trows[0].find_all('th')] # Grabs the header info if headerow: # if there is a header row, include first data.append(headerow) trows = trows[1:] for tr in trows: # assigns each row to the table cols = tr.find_all('td') cols = [ele.text.strip() for ele in cols] data.append([ele for ele in cols if ele]) # Grabs the new and old data to compare in a DataFrame if loop == 0: data_new = pd.DataFrame(data[1:],columns=data[0]) date_new = item.datetime_sent if t == 1: # Makes blank DataFrame if this is the first email in the folder data_pass = pd.DataFrame(data[1:],columns = data[0]) date_old = date_new elif loop == 1: data_old = pd.DataFrame(data[1:],columns=data[0]) date_old = item.datetime_sent loop += 1 # Determines the net change between the emails based on the number of rows netc = [] newsts = len(data_new) oldsts = len(data_old) #Determines the net change to give reference if its a sytem being added or removed if newsts < oldsts: netc = "Net Change = "+str([newsts-oldsts])+" Therefore most likely stations back online." elif newsts > oldsts: netc = "Net Change = "+str([newsts-oldsts])+". Therefore most likely more stations are off online." elif newsts == oldsts: netc = "Net Change = "+str([newsts-oldsts])+". Most likely no change." # Compares the tables if t > 1: # Perform the comparison if there are more than 1 emails in the folder differ = pd.concat([data_new,data_old]) differ = differ.reset_index(drop=True) differ_gpby = differ.groupby(list(differ.columns)) idx = [x[0] for x in differ_gpby.groups.values() if len(x)==1] # Puts the table in HTML for message dif = differ.reindex(idx) dif_html = pd.DataFrame.to_html(dif) elif t == 1: # Assigns all values of emauil added if this is the first email dif_html = pd.DataFrame.to_html(data_pass) # Constructs the response email body tit = HTMLBody("<html><body><p>"+netc+"</p>"+dif_html+"</body></html>") # Composes change email to return (can go to any email) m = Message( account=a, subject = tag+"DMAS Alert Change from: "+str(date_old), body = tit, to_recipients = [Mailbox(email_address='email(s)toRecieveWarning')] ) # Send away! m.send()
def send(recipients, invoice_ref, email_settings, progress=None): """Construct email from Recipient object and send. Parameters ----------- recipients : list A list of recipient objects invoice_ref : str Identifier of the invoice being emailed email_settings : dict configuration settings for exchange server progress: PyQt progress bar """ username = email_settings["username"] password = email_settings["password"] credentials = Credentials(username=username, password=password) config = Configuration( server=email_settings["server"], credentials=credentials ) account = Account( primary_smtp_address=email_settings["from_address"], config=config, autodiscover=False, access_type=DELEGATE ) cc_address = None for rid, recipient in enumerate(recipients): print(recipient.bcode) if email_settings["test_mode"]: to_address = [ Mailbox(email_address=email_settings["test_address"]) ] else: to_address = [ Mailbox(email_address=address) for address in recipient.addresses["to_email"] ] cc_address = [ Mailbox(email_address=address) for address in recipient.addresses["cc_email"] ] if email_settings["copy_manager"]: cc_address.append( Mailbox(email_address=email_settings["manager_address"]) ) if recipient.group.send_only_admin: address = [ Mailbox(email_address=address) for address in recipient.addresses["cc_email"] ] cc_address = "" m = Message( account=account, folder=account.sent, subject=( 'NIC@KCL: Invoice {0}' .format(invoice_ref) ), to_recipients=to_address, cc_recipients=[] ) if cc_address: m.cc_recipients = cc_address print("address: {}".format(m.to_recipients)) print("cc_address: {}".format(m.cc_recipients)) m.body = HTMLBody(recipient.html) m.send_and_save() if progress is not None: progress.emit(rid)