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 handle_create(self, reservation): if not reservation.reserver_email_address: return if not reservation.reserver_email_address.endswith( settings.OUTLOOK_EMAIL_DOMAIN): return unit_address = reservation.resource.unit.address_postal_full if reservation.resource.unit.address_postal_full else reservation.resource.unit.street_address manager = store.items.get(self.id) appointment = CalendarItem( account=manager.account, folder=manager.calendar, subject='Reservation created', body='You have created an reservation', start=ToEWSDateTime(reservation.begin), end=ToEWSDateTime(reservation.end), categories=[], location=unit_address, required_attendees=[ Attendee(mailbox=Mailbox( email_address=reservation.reserver_email_address), response_type='Accept') ]) Mailbox.get_field_by_fieldname( 'routing_type').supported_from = EXCHANGE_2016 appointment.save() self.create_respa_outlook_reservation( appointment=appointment, reservation=reservation, email=reservation.reserver_email_address)
def sendMail(self, sendEmail: SendEmail) -> bool: to_recipients = [] cc_recipients = [] bcc_recipients = [] if not sendEmail.to and not sendEmail.cc: raise Exception('Trying to send email without recepients') for rec in sendEmail.to.split(';'): if rec == "": continue to_recipients.append(Mailbox(email_address=rec)) for rec in sendEmail.cc.split(';'): if rec == "": continue cc_recipients.append(Mailbox(email_address=rec)) for rec in sendEmail.bcc.split(';'): if rec == "": continue bcc_recipients.append(Mailbox(email_address=rec)) Message(account=self.account, subject=sendEmail.subject, body=sendEmail.body, to_recipients=to_recipients, cc_recipients=cc_recipients, bcc_recipients=bcc_recipients).send_and_save()
def test_resolvenames(self): with self.assertRaises(ValueError): self.account.protocol.resolve_names(names=[], search_scope='XXX') with self.assertRaises(ValueError): self.account.protocol.resolve_names(names=[], shape='XXX') self.assertGreaterEqual( self.account.protocol.resolve_names(names=['*****@*****.**']), [] ) self.assertEqual( self.account.protocol.resolve_names(names=[self.account.primary_smtp_address]), [Mailbox(email_address=self.account.primary_smtp_address)] ) # Test something that's not an email self.assertEqual( self.account.protocol.resolve_names(names=['foo\\bar']), [] ) # Test return_full_contact_data mailbox, contact = self.account.protocol.resolve_names( names=[self.account.primary_smtp_address], return_full_contact_data=True )[0] self.assertEqual( mailbox, Mailbox(email_address=self.account.primary_smtp_address) ) self.assertListEqual( [e.email.replace('SMTP:', '') for e in contact.email_addresses if e.label == 'EmailAddress1'], [self.account.primary_smtp_address] )
def _handle_recipients(self, recipients, cc, bcc): recipients = [ Mailbox(email_address=p.split("ex:")[1]) if "ex:" in p else p for p in recipients ] cc = [Mailbox(email_address=p.split("ex:")[1]) if "ex:" in p else p for p in cc] bcc = [ Mailbox(email_address=p.split("ex:")[1]) if "ex:" in p else p for p in bcc ] return recipients, cc, bcc
def Email(subject, body, to, cc=None): m = Message(account=account, subject=subject, body=body, to_recipients=[Mailbox(email_address=to)], cc_recipients=[Mailbox(email_address=cc)]) # 附件加"rb" cont = open(excelName, 'rb').read() attach = FileAttachment(name=excelName, content=cont) m.attach(attach) m.send_and_save()
def test_resolvenames_parsing(self): # Test static XML since server has no roomlists ws = ResolveNames(self.account.protocol) xml = b'''\ <?xml version="1.0" encoding="utf-8"?> <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"> <s:Header> <h:ServerVersionInfo MajorVersion="15" MinorVersion="0" MajorBuildNumber="1293" MinorBuildNumber="4" Version="V2_23" xmlns:h="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/> </s:Header> <s:Body> <m:ResolveNamesResponse xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages" xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"> <m:ResponseMessages> <m:ResolveNamesResponseMessage ResponseClass="Warning"> <m:MessageText>Multiple results were found.</m:MessageText> <m:ResponseCode>ErrorNameResolutionMultipleResults</m:ResponseCode> <m:DescriptiveLinkKey>0</m:DescriptiveLinkKey> <m:ResolutionSet TotalItemsInView="2" IncludesLastItemInRange="true"> <t:Resolution> <t:Mailbox> <t:Name>John Doe</t:Name> <t:EmailAddress>[email protected]</t:EmailAddress> <t:RoutingType>SMTP</t:RoutingType> <t:MailboxType>Mailbox</t:MailboxType> </t:Mailbox> </t:Resolution> <t:Resolution> <t:Mailbox> <t:Name>John Deer</t:Name> <t:EmailAddress>[email protected]</t:EmailAddress> <t:RoutingType>SMTP</t:RoutingType> <t:MailboxType>Mailbox</t:MailboxType> </t:Mailbox> </t:Resolution> </m:ResolutionSet> </m:ResolveNamesResponseMessage> </m:ResponseMessages> </m:ResolveNamesResponse> </s:Body> </s:Envelope>''' header, body = ws._get_soap_parts(response=MockResponse(xml)) res = ws._get_elements_in_response(response=ws._get_soap_messages( body=body)) self.assertSetEqual( { Mailbox.from_xml(elem=elem.find(Mailbox.response_tag()), account=None).email_address for elem in res }, {'*****@*****.**', '*****@*****.**'})
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 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(): ''' function to send email with the zip file as attachment ''' m = Message( account=a, subject='AUTOMATED DISCOUNT OVERLAP REPORT ' + str(today), body = HTMLBody("Dear ALL, <br/><br/> Please find attached report. <br/><br/>The report is also accessible at the following address: <br/><a style='color:blue; text-decoration:underline'>link here</a> "), to_recipients=[ Mailbox(email_address='*****@*****.**') ], cc_recipients=['*****@*****.**'], # Simple strings work, too # bcc_recipients=[ # Mailbox(email_address='*****@*****.**'), # '*****@*****.**', #], # Or a mix of both ) attachments=[] with open(str(getFile('.zip')) + '.zip', 'rb') as f: content = f.read() attachments.append((str(getFile('.zip')) + '.zip', content)) for attachment_name, attachment_content in attachments: file = FileAttachment(name=attachment_name, content=attachment_content) m.attach(file) m.send_and_save()
def send_exchange_email(from_addr: str, to_addr: str, sub: str, body: str, account: str, pwd: str, user_name: str): """ Sends email using Exchange :param from_addr: :param to_addr: :param sub: :param body: :param account: :param pwd: :param user_name: :return: """ creds = Credentials(user_name, pwd) config = Configuration(server=account, credentials=creds) account = Account(primary_smtp_address=from_addr, autodiscover=False, access_type=DELEGATE, config=config) msg = Message( account=account, folder=account.sent, subject=sub, body=body, to_recipients=[Mailbox(email_address=to_addr)]) msg.send_and_save()
def bulk_send_exchange_email(from_addr: str, sub: str, account: str, pwd: str, user_name: str, names_list: str, content_file: str, sheet: str, signature: str): """ Sends email using Exchange :param from_addr: :param sub: :param account: :param pwd: :param user_name: :param content_file: :param names_list: :param sheet: :param signature: :return: """ recipients = spreadsheet_data(names_list, sheet) body = content_from_file(content_file) signature = content_from_file(signature) creds = Credentials(user_name, pwd) config = Configuration(server=account, credentials=creds) account = Account(primary_smtp_address=from_addr, autodiscover=False, access_type=DELEGATE, config=config) for item in recipients: complete_email = 'Hello ' + item['First_Name'] + '\n\n' + body + '\n' + signature email_address = item['Email_Address'] msg = Message( account=account, folder=account.sent, subject=sub, body=complete_email, to_recipients=[Mailbox(email_address=email_address)]) msg.send_and_save()
async def send_email( self, username, password, server, build, account, verifyssl, recipient, subject, body, ): # Authenticate auth = await self.authenticate(username, password, server, build, account, verifyssl) if auth["error"]: return auth["error"] account = auth["account"] m = Message( account=account, subject=subject, body=body, to_recipients=[ Mailbox(email_address=address) for address in recipient.split(", ") ], ) m.send() return {"ok": True, "error": False}
def Email(self,to, subject, body,email_type, attachments=None): creds = Credentials(username=self.localVariable["__EMAILEX__"], password=self.localVariable["__EMAILEX_PASSWORD__"]) config = Configuration(server='outlook.office365.com',credentials=creds) account = Account( primary_smtp_address=self.localVariable["__EMAILEX__"], config=config, # credentials=creds, autodiscover=False, access_type=DELEGATE ) m = Message( account=account, subject=subject, body=HTMLBody(body), to_recipients = [Mailbox(email_address=to)] ) if attachments: m.attach(attachments) if email_type==1 and to in list(self.localStore.keys()): print("清除 %s" % to) self.localStore.pop(to) try: m.send() if email_type == 0: message = u"验证码已发送邮箱!" else: message = u"证书已发送邮箱!" return message except: message = u"发送失败!" return message
def send_email(title='报警邮件', recervers='*****@*****.**', msg='content', file_name=''): try: credentials = Credentials(username, password) config = Configuration(server=r_server, credentials=credentials) account = Account(username, autodiscover=False, config=config, access_type=DELEGATE) except Exception as e: print('错误: {0}'.format(e)) sys.exit(1) m = Message( account=account, subject=title, body=HTMLBody(msg), to_recipients=[Mailbox(email_address=x) for x in recervers.split(',')]) if file_name: with open(os.path.abspath(r"../work_flow/sre.xls"), "rb") as f: cont = f.read() attchF = FileAttachment(name='值班表.xls', content=cont) m.attach(attchF) m.send_and_save() else: m.send()
def generate_email(account, body, recipient, hb): ''' The function gets called for each recipient. Emails are saved in the Drafts folder for human review ''' m = Message( account=account, folder=account.drafts, subject='Discovery alert', body=HTMLBody(body), to_recipients=[Mailbox(email_address=recipient)] ) root_path = join(os.getcwd(), 'pyalerts') hb_temp_path = join(root_path, "temp", f"temp_{hb}") for image_basename in os.listdir(hb_temp_path): image_path = join(hb_temp_path, image_basename) with open(image_path, 'rb') as f: embed_image = FileAttachment( name=image_path, content_id=os.path.basename(image_path), content=f.read(), is_inline=True) m.attach(embed_image) m.save()
def release(content, driver, account): transactionIndex = content.find("Transaction:") transaction = content[transactionIndex:content[transactionIndex:]. find("\n") + transactionIndex] ccnIndex = content.find("Cargo Control Number:") releaseIndex = content.find("Release Office: ") ccn = content[ccnIndex + 22:releaseIndex].strip() transaction = transaction + "\n" + content[ccnIndex:content[ccnIndex:]. find("\n") + ccnIndex] deliveryIndex = content.find("Delivery Instructions") - 2 containerIndex = content.find("Container ID(s):") + 17 containers = [] if containerIndex < deliveryIndex: while containerIndex < deliveryIndex: containers.append( content[containerIndex:content[containerIndex:].find(",") + containerIndex].strip()) containerIndex = content[containerIndex:].find( ",") + 1 + containerIndex print("\nReleasing the following containers: ") for cont in containers: sendRelease(cont, transaction, driver, account) else: m = Message( account=account, subject='CCN is Released: ' + ccn, body='PB #(if Seaport CCN): ' + ccn[-6:] + "\n\nThe RNS release message did not have a container number in it\n\n\nTHIS IS AN AUTOMATED MESSAGE, DO NOT REPLY", to_recipients=[ Mailbox(email_address='*****@*****.**'), ]) m.send() print("\nEmail with no container number")
def send_email(subject, body, recipients, attachments=None): """ 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)) # 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 []: file = FileAttachment(name=attachment_name, content=attachment_content) m.attach(file) m.send_and_save()
def ews_send_email(ews_account, subject, body, recipient, attachments=None): ''' Email -> Recipient Attachments are python dictionary {FileName : FileContent} Moves the sent email into the 'Outbound' folder ''' try: # Setup empty dict if attachments is None: attachments = [] # Prep email message email_draft = Message(account=ews_account, folder=ews_account.inbox / 'Outbound', subject=subject, body=body, to_recipients=[Mailbox(email_address=recipient)]) for dict_key in attachments: attachment = FileAttachment(name=dict_key, content=attachments[dict_key]) email_draft.attach(attachment) # Send the Email email_draft.send_and_save() # Mark the sent email as unread ews_toggle_is_read(ews_account, 'Outbound') except Exception as error_text: print(f'[Error] Unable to send email - {str(error_text)}') sys.exit()
def send_email(content, exchange_host, mailbox, mail_user, mail_password, dest_address): """ Sends an email to dest_address containing the list of potential malicious new domains. """ from exchangelib import DELEGATE, Account, Configuration, Credentials, Message, Mailbox message = "Found the following potential malicious new domains: {}".format( content) creds = Credentials(username=mail_user, password=mail_password) serverconfig = Configuration(server=exchange_host, credentials=creds) account = Account(primary_smtp_address=mailbox, credentials=creds, autodiscover=False, config=serverconfig, access_type=DELEGATE) if account: print("Authenticated as {} to O365 succeeded.".format(mail_user)) else: print("Authentication to O365 mailbox as {} has failed.".format( mail_user)) sys.exit(-1) m = Message(account=account, subject='New domain alert', body=message, to_recipients=[ Mailbox(email_address=dest_address), ]) m.send() print("Email has been sent to {}.".format(dest_address))
def email(self, to, subject, body): """ 发送邮件 :param to: 接收人 :param subject: 邮件主题 :param body: 邮件内容 :return: """ creds = Credentials( username=self.email_name, password=self.email_password ) account = Account( primary_smtp_address=self.email_name + '@taoche.com', credentials=creds, autodiscover=True, access_type=DELEGATE ) m = Message( account=account, subject=subject, body=HTMLBody(body), to_recipients=[Mailbox(email_address=i) for i in to] ) m.send()
def generate_email(invite): # Create message container - the correct MIME type is multipart/alternative. subject = "Please register for your DevOps, Developer and Automation training portal access" # Customize this to your own message. html = """\ <html> <body> <p>Hi,<br><br> Happy New Year. You should have received emails from me regarding access to pluralsight.com, invitations are limited to a small group of individuals, of which you are one. Invitations will expire/be reallocated for any users that have not accepted their invitations by the deadline. <br><br> This is your unique registration link - <a href="{0}">{0}</a>. <br><br> Please register this week, <u>do not forward this email</u>. Registration links are unique.<br><br> Regards,<br> </p> </body> </html> """.format(invite.generate_url(plan)) return Message(account=account, folder=account.sent, subject=subject, body=HTMLBody(html), to_recipients=[Mailbox(email_address=invite.email)])
def send_with_exchange(username, password, server, address, content, subject='', to_recipients=[], attachements=[]): credentials = Credentials(username=username, password=password) config = Configuration(server=server, credentials=credentials) account = Account( primary_smtp_address=address, autodiscover=False, config=config, credentials=credentials, access_type=DELEGATE) _to_recipients = [] for item in to_recipients: _to_recipients.append(Mailbox(email_address=item['email'])) m = Message( account=account, subject=subject, body=HTMLBody(content), to_recipients=_to_recipients) if attachements: for item in attachements: with open(item['src'], 'rb') as f: img_attach = FileAttachment(name=item['name'], content=f.read()) m.attach(img_attach) m.send()
def send(self, to, body): m = Message(account=self.account, folder=self.account.sent, subject="Personal tutor attendance data", body=HTMLBody(body), to_recipients=[Mailbox(email_address=to)]) m.send_and_save()
def _send(self, email_message): """A helper method that does the actual sending.""" if not email_message.recipients(): return False encoding = email_message.encoding or settings.DEFAULT_CHARSET from_email = sanitize_address(email_message.from_email, encoding) recipients = [ sanitize_address(addr, encoding) for addr in email_message.recipients() ] try: account = Account(primary_smtp_address=from_email, credentials=self.credentials, autodiscover=True, access_type=DELEGATE) exchange_message = Message(account=account, subject=email_message.subject, body=email_message.body, to_recipients=[ Mailbox(email_address=recipient) for recipient in recipients ]) exchange_message.send() except Exception: if not self.fail_silently: raise return False return True
def get_ips_and_send_scanmail(task, task_1, task_2): list_name_id = get_sysinfo() id = list_name_id[task] email_address = get_user_mail(id) now = datetime.datetime.now() + datetime.timedelta(1) now = now.strftime("%Y年%m月%d日") the_system = task with open(task, "a+") as f: if (os.path.exists(task_1)): with open(task_1, "r+") as f1: f.write(f1.read()) if (os.path.exists(task_2)): with open(task_2, "r+") as f2: f.write(f2.read()) with open(task, "r+") as f: data_r = """ <table border="1" cellspacing=0> <tr> <th>系统</th> <th>资产</th> </tr>\r\n """ ips = f.readlines() for ip in ips: sytem_info = "ceshi" ip = ip.replace("\n", "") data_cow = "<tr>\r\n" + "<td>" + task + "</td>\r\n" + "<td>" + ip + "</td>" + "\r\n</tr>" data_r = data_r + data_cow data_r = data_r + "\r\n</table>" print(data_r) data = f""" <br> 您好, <br> 我方将于今晚凌晨12点对以下系统进行漏洞扫描,开展扫描工作事项如下: <br><b> 1、扫描对象:</b> <br> {the_system} <br><b> 2、扫描时间:</b> <br> {now}凌晨0:00至{now}早上8:30 <br><b style="background-color: rgb(255,255,0)"> 3、注意事项:</b> <br> a、对于扫描的系统是否有扫描时间要求。 <br> b、<t style="background-color: rgb(255,255,0);color:red">对漏洞扫描资产是否有需要剔除、确认系统资产是否有误。</t> <br> 附:可能受影响出现的情况 : <br> 有可能会对被测网络设备或主机造成异常运行; <br> 有可能会对被测主机上的各种服务和应用程序造成异常运行; <br> 扫描期间,被测主机上的各种服务的运行速度可能会减慢; <br> 扫描期间,网络的处理能力和传输速度可能会减慢; <br> <br> 详细资产请参考以下IP: <br> {data_r} <br> <br> 如发现异常,请及时联系 <br> ************************** <br> ********** """ m = Message(account=account, subject=str(today) + task + "扫描通知", body=HTMLBody(data), to_recipients=[Mailbox(email_address=email_address[0])], cc_recipients=["**********", "**********"]) m.send_and_save() return
def __gen_email_list(emails): from exchangelib import Mailbox objs = list() for email in emails: objs.append(Mailbox(email_address=email)) return objs
def sendMessage(self, to, subject, body, attachmentBytes=None, attachmentName="file.txt"): if self.account is not None: self.lock.acquire() m = Message(account=self.account, to_recipients=[Mailbox(email_address=to.strip())], subject=subject.strip(), body=HTMLBody(body)) if attachmentBytes is not None: f = FileAttachment(name=attachmentName, content=attachmentBytes) m.attach(f) m.send() self.lock.release()
def test_mailbox(self): mbx = Mailbox(name='XXX') with self.assertRaises(ValueError): mbx.clean() # Must have either item_id or email_address set mbx = Mailbox(email_address='XXX') self.assertEqual(hash(mbx), hash('xxx')) mbx.item_id = 'YYY' self.assertEqual(hash(mbx), hash('YYY')) # If we have an item_id, use that for uniqueness
def sendMessage(recipient, subject, body): try: m = Message(account=account, folder=account.sent, subject=subject, body=body, to_recipients=[Mailbox(email_address=recipient)]) except Exception as e: print("\nfailed sending email.\n", str(e)) m.send_and_save()