def get_ewsmessage(self, account): from exchangelib import Account, Message, Mailbox, FileAttachment, HTMLBody, Credentials, Configuration, NTLM, DELEGATE m = Message(account=account, subject=self.subject, body=HTMLBody(self.html), to_recipients=[self.toheader]) if self.readreceipt: m.is_read_receipt_requested = True if len(self.headers) > 0: print 'Custom mail headers not currently supported in EWS mode' # for k,v in self.headers: # This is fiddly, not enabled yet # Find any embedded images and attach attachments = re.findall('src="cid:([^"]+)"', self.html) for attachment in attachments: a = FileAttachment(name=attachment, content=open(attachment, "rb").read(), is_inline=True, content_id=attachment) m.attach(a) # Optional attachment for attachment in self.attachments: a = FileAttachment(name=attachment, content=open(attachment, "rb").read()) m.attach(a) return m
def process_attachments(attachCIDs="", attachIDs="", attachNames="", manualAttachObj=None): if manualAttachObj is None: manualAttachObj = [] file_entries_for_attachments = [] # type: list attachments_names = [] # type: list if attachIDs: file_entries_for_attachments = attachIDs if isinstance( attachIDs, list) else attachIDs.split(",") if attachNames: attachments_names = attachNames if isinstance( attachNames, list) else attachNames.split(",") else: for att_id in file_entries_for_attachments: att_name = demisto.getFilePath(att_id)['name'] if isinstance(att_name, list): att_name = att_name[0] attachments_names.append(att_name) if len(file_entries_for_attachments) != len(attachments_names): raise Exception( "attachIDs and attachNames lists should be the same length") attachments = collect_manual_attachments(manualAttachObj) if attachCIDs: file_entries_for_attachments_inline = attachCIDs if isinstance( attachCIDs, list) else attachCIDs.split(",") for att_id_inline in file_entries_for_attachments_inline: try: file_info = demisto.getFilePath(att_id_inline) except Exception as ex: demisto.info("EWS error from getFilePath: {}".format(ex)) raise Exception("entry %s does not contain a file" % att_id_inline) att_name_inline = file_info["name"] with open(file_info["path"], 'rb') as f: attachments.append( FileAttachment(content=f.read(), name=att_name_inline, is_inline=True, content_id=att_name_inline)) for i in range(0, len(file_entries_for_attachments)): entry_id = file_entries_for_attachments[i] attachment_name = attachments_names[i] try: res = demisto.getFilePath(entry_id) except Exception as ex: raise Exception("entry {} does not contain a file: {}".format( entry_id, str(ex))) file_path = res["path"] with open(file_path, 'rb') as f: attachments.append( FileAttachment(content=f.read(), name=attachment_name)) return attachments, attachments_names
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 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 _add_attachments_to_msg(self, attachments, msg): for attachment in attachments: attachment = attachment.strip() with open(attachment, "rb") as f: atname = str(Path(attachment).name) fileat = FileAttachment(name=atname, content=f.read()) msg.attach(fileat)
def send_smtp(self, attachment=None): msg = MIMEMultipart('alternative') msg['Subject'] = self.subject msg['To'] = self.to_field msg['From'] = self.from_field logger.debug(print( 'the html_body is a ' + type(self.html_body) + ' datatype.' ) part2 = MIMEText(self.html_body, 'html') msg.attach(part2) try: mail = smtplib.SMTP('smtp.gmail.com', 587) mail.ehlo() mail.starttls() mail.login(self.secrets['username'], self.secrets['password']) mail.sendmail(self.from_address, self.from_address, msg.as_string()) mail.quit() logger.info(f'\n--> Email sent with subject: "{self.subject}"\n') except: logger.error('Failed to connect to smtp server') def send_exchange(self, attachment=None): ''' Authenticates with exchave server and sends an email ''' self.connect_to_exchange() m = Message( account=self.ews_account, subject=self.subject, body=HTMLBody(self.template.render( subject=self.subject, body=self.html_body)), to_recipients=[self.to_address], # defaults to sending yourself an email cc_recipients=[''], # bcc_recipients=[], ) if type(attachment) is str: attachment_filepath = os.path.join( os.getcwd(), attachment) with open(attachment_filepath, 'rb') as f: binary_file_content = f.read() logger.info(f'Attaching {attachment} to the report') m.attach(FileAttachment(name=attachment, content=binary_file_content)) if self.images: self.attach_images() m.send() logger.info(f'--> Email sent with subject: "{self.subject}"')
def test_pickle(self): # Test that we can pickle various objects item = Message(folder=self.account.inbox, subject='XXX', categories=self.categories).save() attachment = FileAttachment(name='pickle_me.txt', content=b'') try: for o in ( item, attachment, self.account.protocol, self.account.root, self.account.inbox, self.account, Credentials('XXX', 'YYY'), FaultTolerance(max_wait=3600), ): pickled_o = pickle.dumps(o) unpickled_o = pickle.loads(pickled_o) self.assertIsInstance(unpickled_o, type(o)) if not isinstance(o, (Account, Protocol, FaultTolerance)): # __eq__ is not defined on some classes self.assertEqual(o, unpickled_o) finally: item.delete()
def post(self): email_addresss = self.get_argument("email") emial_code = self.get_argument("code") code_local = None email_local = self.localStore.get(email_addresss) if email_addresss in list(self.localStore.keys()): print(self.localStore) code_local = self.localStore.get(email_addresss) else: return self.write(json.dumps({"msg": u"验证码过期,请重新获取!"})) print("local:", code_local, "ui:", emial_code, "localemail:", email_local) if code_local is None: return self.write(json.dumps({"msg": u"验证码过期!"})) # print(codeEmailPwd.get("emailCode")) if code_local.upper() != emial_code.upper(): return self.write(json.dumps({"msg":u"验证码过期!"})) receivers = [] receivers.append(email_addresss) try: filename = "FileAttachment.txt" with open(filename, 'rb') as f: my_files = FileAttachment(name=filename, content=f.read()) message = Email(self,receivers[0], mail_subject, mail_msg_ca, 1, my_files) return self.write(json.dumps({"msg": message})) except Exception as e: print(e) return self.write(json.dumps({"msg": u"验证码生成失败!"}))
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 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_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 send_mail_exchange(config, recipients, subject, body, attachments): """Sends the supplied message through an Exchange connection to the list of recipients""" # Gathering email account details user = config["Email"] password = encryption.get_password() # Connecting to Exchange account account = None try: credentials = Credentials(user, password) account = Account(user, credentials=credentials, autodiscover=True) logger.debug("Exchange connection successful") except Exception as e: logger.error("Could not connect to Exchange Email: " + str(e)) return # Constructing message message = Message(account=account, subject=subject, body=body, to_recipients=recipients.replace(", ", ",").split(",")) # Attaching files for image_path in attachments: with open(image_path, 'rb') as f: repImage = FileAttachment(name=os.path.basename(image_path), content=f.read()) message.attach(repImage) # Sending message.send_and_save()
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 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 send_email(account, email_message_dict, attachments, message_uuid, dry_run): logging.debug(f"Saving {message_uuid}.json to Minio") with tempfile.TemporaryDirectory() as tempdir: local_path = os.path.join(tempdir, f"{message_uuid}.json") with open(local_path, "w") as message_file: json.dump(email_message_dict, message_file) minio_utils.file_to_minio( filename=local_path, minio_bucket=EMAILS_BUCKET, minio_key=secrets["minio"]["edge"]["access"], minio_secret=secrets["minio"]["edge"]["secret"], data_classification=EDGE_CLASSIFICATION, ) message = Message(account=account, **email_message_dict) logging.debug("Attaching logo") logo_path = os.path.join(RESOURCES_PATH, CITY_LOGO_FILENAME) with open(logo_path, "rb") as logo_file: message.attach( FileAttachment(name=CITY_LOGO_FILENAME, content=logo_file.read())) logging.debug(f"Attaching data files") for attachment_name, attachment_file in attachments: logging.debug(f"attachment_name='{attachment_name}'") with open(attachment_file, "rb") as plot_file: message.attach( FileAttachment(name=attachment_name, content=plot_file.read())) logging.debug(f"Sending {message_uuid} email") # Turning down various exchange loggers for the send - they're a bit noisy exchangelib_loggers = [ logging.getLogger(name) for name in logging.root.manager.loggerDict if name.startswith("exchangelib") ] for logger in exchangelib_loggers: logger.setLevel(logging.INFO) if not dry_run: message.send(save_copy=True) else: logging.warning("**--dry_run flag set, hence not sending emails...**") return True
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 collect_manual_attachments(manualAttachObj): attachments = [] for attachment in manualAttachObj: res = demisto.getFilePath(os.path.basename(attachment['RealFileName'])) file_path = res["path"] with open(file_path, 'rb') as f: attachments.append(FileAttachment(content=f.read(), name=attachment['FileName'])) return attachments
def _add_images_inline_to_msg(self, images, html, body, msg): for image in images: image = image.strip() with open(image, "rb") as f: imname = str(Path(image).name) fileat = FileAttachment(name=imname, content=f.read(), content_id=imname) msg.attach(fileat) if html: body = body.replace(imname, f"cid:{imname}")
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 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( self, username, password, server, build, account, verifyssl, recipient, subject, body, attachments, ): # Authenticate auth = self.authenticate(username, password, server, build, account, verifyssl) if auth["error"]: return { "success": False, "reason": auth["error"], } account = auth["account"] m = Message( account=account, subject=subject, body=body, to_recipients=[ Mailbox(email_address=address) for address in recipient.split(", ") ], ) file_uids = attachments.split() if len(file_uids) > 0: for file_uid in file_uids: attachment_data = self.get_file(file_uid) file = FileAttachment(name=attachment_data["filename"], content=attachment_data["data"]) m.attach(file) ret = m.send() print(ret) return { "success": True, "error": False, "recipients": recipient, "subject": subject }
def send_email(to, subject, body="", bcc=None, cc=None, replyTo=None, htmlBody=None, attachIDs="", attachNames="", from_mailbox=None, manualAttachObj=None): account = get_account(from_mailbox or ACCOUNT_EMAIL) bcc = bcc.split(",") if bcc else None cc = cc.split(",") if cc else None to = to.split(",") if to else None manualAttachObj = manualAttachObj if manualAttachObj is not None else [] subject = subject[:252] + '...' if len(subject) > 255 else subject file_entries_for_attachments = [] # type: list attachments_names = [] # type: list if attachIDs: file_entries_for_attachments = attachIDs.split(",") if attachNames: attachments_names = attachNames.split(",") else: for att_id in file_entries_for_attachments: att_name = demisto.getFilePath(att_id)['name'] if isinstance(att_name, list): att_name = att_name[0] attachments_names.append(att_name) if len(file_entries_for_attachments) != len(attachments_names): raise Exception("attachIDs and attachNames lists should be the same length") attachments = collect_manual_attachments(manualAttachObj) for i in range(0, len(file_entries_for_attachments)): entry_id = file_entries_for_attachments[i] attachment_name = attachments_names[i] try: res = demisto.getFilePath(entry_id) except Exception as ex: raise Exception("entry {} does not contain a file: {}".format(entry_id, str(ex))) file_path = res["path"] with open(file_path, 'rb') as f: attachments.append(FileAttachment(content=f.read(), name=attachment_name)) send_email_to_mailbox(account, to, subject, body, bcc, cc, replyTo, htmlBody, attachments) result_object = { 'from': account.primary_smtp_address, 'to': to, 'subject': subject, 'attachments': attachments_names } return { 'Type': entryTypes['note'], 'Contents': result_object, 'ContentsFormat': formats['json'], 'ReadableContentsFormat': formats['markdown'], 'HumanReadable': tableToMarkdown('Sent email', result_object), }
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 add_attachment(self): """ Add attachment if there's one """ #: FIXME: fix this shit to always work with any attachment. i.e. Excel/pdfs/word docs/images for i in self.attachment: """ self.attachment is a dict, the values, are paths that point to the file to be read""" with open(i['full_path'], 'rb') as f: my_attacment = f.read() """ create File attachment""" this_attachment = FileAttachment(name=i['name'],\ content=my_attacment) """ attach the file to the msg""" self.msg.attach(this_attachment) return
def attach_file(self, message, file_path, file_name): """Attaches a given file to a given message, and names as specified. :param message: (Message) A message object (from exchangelib) that you wish to attach a file to :param file_path: (String) A string containing the filepath of the file you wish to attach :param file_name: (String) A string that specifies what you want the reciever to see as the name of the file :return: (Message) The message with a new file attachment """ attachment = '' with open(file_path, 'rb') as f: attachment = FileAttachment(name=file_name, content=f.read()) message.attach(attachment) return message
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 []: file = FileAttachment(name='Code', content=f) m.attach(file) m.send_and_save()
def send(account=account, subject=subject, body=body, recipients=recipients, attachments=[]): """ Send an email. Parameters ---------- account : Account object subject : str body : str recipients : list of str Each str is an email adress attachments : list of str Each str is a path of file 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, subject=subject, body=body, to_recipients=to_recipients) # Read attachment # attachments : list of tuples or None # (filename, binary contents) files = [] for file in attachments: with open(file, 'rb') as f: content = f.read() files.append((file, content)) # attach files for attachment_name, attachment_content in files or []: file = FileAttachment(name=attachment_name, content=attachment_content) m.attach(file) m.send()
def send_email(account, subject, body, recipients, attachments=None): 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() logger.info("Email sent successfully")
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 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