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 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_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 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 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 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_email_to_mailbox(account, to, subject, body, bcc=None, cc=None, reply_to=None, html_body=None, attachments=[], raw_message=None, from_address=None): 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(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_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 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(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 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 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 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_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 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_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 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
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 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 sendmail_win_cs(filename, email): target_filename = filename + '*.csv' newest = max(glob.iglob(target_filename), key=os.path.getctime) print('newest file: ' + newest) today_date = datetime.datetime.now().strftime('%y%m%d') try: newest_date = re.search(filename + '(\d+)', newest).group(1) except AttributeError: newest_date = '' print('newest date: ' + newest_date) if newest_date != today_date: print( 'Error: newest date != today date.. mannual intervention needed..') return print('Setting account..') # Username in WINDOMAIN\username format. Office365 wants usernames in PrimarySMTPAddress # ('*****@*****.**') format. UPN format is also supported. credentials = Credentials(username='******', password=sendmail_secret['password']) print('Discovering..') # If the server doesn't support autodiscover, use a Configuration object to set the server # location: config = Configuration(server='emailuk.kuoni.com', credentials=credentials) try: account = Account(primary_smtp_address=email, config=config, autodiscover=False, access_type=DELEGATE) except ConnectionError as e: print('Fatal: Connection Error.. aborted..') return print('Logged in as: ' + str(email)) recipient_email = '*****@*****.**' recipient_email1 = '*****@*****.**' recipient_email2 = '*****@*****.**' recipient_email3 = '*****@*****.**' recipient_email4 = '*****@*****.**' recipient_email6 = '*****@*****.**' recipient_email5 = '*****@*****.**' body_text = 'FYI\n' + \ 'Best\n' + \ '-Yu' title_text = '[[[ Ctrip hotel reference ]]]' # Or, if you want a copy in e.g. the 'Sent' folder m = Message( account=account, folder=account.sent, sender=Mailbox(email_address=email), author=Mailbox(email_address=email), subject=title_text, body=body_text, # to_recipients=[Mailbox(email_address=recipient_email1), # Mailbox(email_address=recipient_email2), # Mailbox(email_address=recipient_email3) # ] # to_recipients=[Mailbox(email_address=recipient_email1), # Mailbox(email_address=recipient_email2), # Mailbox(email_address=recipient_email3), # Mailbox(email_address=recipient_email4), # Mailbox(email_address=recipient_email5) # ] to_recipients=[ Mailbox(email_address=recipient_email1), Mailbox(email_address=recipient_email2), Mailbox(email_address=recipient_email3), Mailbox(email_address=recipient_email4) ]) with open(newest, 'rb') as f: update_csv = FileAttachment(name=newest, content=f.read()) m.attach(update_csv) m.send_and_save() print('Message sent.. ')
def sendmail_win_hb2(filename, email): target_filename = filename + '*.csv' newest = max(glob.iglob(target_filename), key=os.path.getctime) print('newest file: ' + newest) today_date = datetime.datetime.now().strftime('%y%m%d') try: newest_date = re.search( filename + '(\d+)', newest).group(1) except AttributeError: newest_date = '' print('newest date: ' + newest_date) if newest_date != today_date: print('Error: newest date != today date.. mannual intervention needed..') return print('Setting account..') # Username in WINDOMAIN\username format. Office365 wants usernames in PrimarySMTPAddress # ('*****@*****.**') format. UPN format is also supported. credentials = Credentials(username='******', password=sendmail_secret['password']) print('Discovering..') # If the server doesn't support autodiscover, use a Configuration object to set the server # location: config = Configuration(server='emailuk.kuoni.com', credentials=credentials) try: account = Account(primary_smtp_address=email, config=config, autodiscover=False, access_type=DELEGATE) except ConnectionError as e: print('Fatal: Connection Error.. aborted..') return print('Logged in as: ' + str(email)) recipient_email = '*****@*****.**' recipient_email1 = '*****@*****.**' recipient_email2 = '*****@*****.**' recipient_email3 = '*****@*****.**' recipient_email4 = '*****@*****.**' recipient_email5 = '*****@*****.**' recipient_email6 = '*****@*****.**' body_text = 'FYI\n\n' + \ 'Key China clients L2B list. Please note that data for the most current week is not complete. \"Percentage\" column is difference between 4th and 5th week. \n\n' + \ 'This is an automated message. Please do not reply.\n\n' + \ 'Best\n' + \ '-Yu Leng' title_text = '[[[ GTA L2B Weekly ]]]' # Or, if you want a copy in e.g. the 'Sent' folder m = Message( account=account, folder=account.sent, sender=Mailbox(email_address=email), author=Mailbox(email_address=email), subject=title_text, body=body_text, # to_recipients=[Mailbox(email_address=recipient_email1), # Mailbox(email_address=recipient_email2), # Mailbox(email_address=recipient_email3) # ] # to_recipients=[Mailbox(email_address=recipient_email1), # Mailbox(email_address=recipient_email2), # Mailbox(email_address=recipient_email3), # Mailbox(email_address=recipient_email4), # Mailbox(email_address=recipient_email5) # ] # to_recipients=[Mailbox(email_address=recipient_email1), # Mailbox(email_address=recipient_email), # Mailbox(email_address=recipient_email2), # Mailbox(email_address=recipient_email3), # Mailbox(email_address=recipient_email4) # ] # to_recipients=[Mailbox(email_address=recipient_email1), # Mailbox(email_address=recipient_email), # Mailbox(email_address=recipient_email2), # Mailbox(email_address=recipient_email3), # Mailbox(email_address=recipient_email4), # Mailbox(email_address=recipient_email5) # ] # to_recipients=[Mailbox(email_address=recipient_email1), # Mailbox(email_address=recipient_email), # Mailbox(email_address=recipient_email2), # Mailbox(email_address=recipient_email3), # Mailbox(email_address=recipient_email4), # Mailbox(email_address=recipient_email5), # Mailbox(email_address=recipient_email6) # ] to_recipients=[Mailbox(email_address=recipient_email1), Mailbox(email_address=recipient_email2), Mailbox(email_address=recipient_email3), Mailbox(email_address=recipient_email4), Mailbox(email_address=recipient_email5), Mailbox(email_address=recipient_email6) ] ) with open(newest, 'rb') as f: update_csv = FileAttachment(name=newest, content=f.read()) m.attach(update_csv) m.send_and_save() print('Message sent.. ')
class OutlookMail: #Initialization def __init__(self, username, password, email): self.username = username self.password = password self.email = email self.subject = None self.account = None self.message = None self.body = None self.myfile = None self.to_recipients = [] self.cc_recipients = [] self.bcc_recipients = [] #Adding recipients function def add_recipients(self, to_recipients, cc_recipients=None, bcc_recipients=None): if cc_recipients is not None: self.cc_recipients.extend(cc_recipients) if bcc_recipients is not None: self.bcc_recipients.extend(bcc_recipients) self.to_recipients.extend(to_recipients) #Adding message subject & body function def add_message(self, subject, body): self.email = self.email self.subject = subject self.body = body self.mail_credentials = Credentials(username=self.username, password=self.password) self.mail_config = Configuration(server='outlook.office365.com', credentials=self.mail_credentials) self.account = Account(primary_smtp_address=self.email, config=self.mail_config, autodiscover=False, access_type=DELEGATE) try: if len(self.bcc_recipients) == 0 and len( self.cc_recipients) == 0 and len(self.to_recipients) != 0: self.message = Message(account=self.account, folder=self.account.sent, subject=self.subject, body=self.body, to_recipients=self.to_recipients) elif len(self.cc_recipients) == 0: self.message = Message(account=self.account, folder=self.account.sent, subject=self.subject, body=self.body, to_recipients=self.to_recipients, bcc_recipients=self.bcc_recipients) elif len(self.bcc_recipients) == 0: self.message = Message(account=self.account, folder=self.account.sent, subject=self.subject, body=self.body, to_recipients=self.to_recipients, cc_recipients=self.cc_recipients) except MissingEmail: print('Missing recipients email addresses.') #Adding attachment def add_attachment(self, file, name): with open(file, 'rb') as f: content = f.read() self.myfile = FileAttachment(name=name, content=content) self.message.attach(self.myfile) #Sending mail def send_mail(self): self.message.send_and_save()