Skip to content

Instantly share code, notes, and snippets.

@AbhishekAshokDubey
Created April 17, 2020 09:44
Show Gist options
  • Save AbhishekAshokDubey/f552bba471fe326de6967127f34ac1b5 to your computer and use it in GitHub Desktop.
Save AbhishekAshokDubey/f552bba471fe326de6967127f34ac1b5 to your computer and use it in GitHub Desktop.
sample email sending API
# -*- coding: utf-8 -*-
"""
@author: abhishek
"""
from exchangelib import Account, Credentials, DELEGATE, Configuration, NTLM, Mailbox, Message, FileAttachment
from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter
def send_email(account, subject , body, to, cc = [], bcc=[], attachment_path = ""):
m = Message(
account=account,
subject=subject,
body=body,
to_recipients = to,
cc_recipients = cc,
bcc_recipients = bcc,
)
if len(attachment_path):
with open(attachment_path, 'rb') as f:
content = f.read()
file = FileAttachment(name=attachment_path.split("\\")[-1], content=content)
m.attach(file)
m.send()
def connect(email, username, password):
"""
Get Exchange account cconnection with server
"""
creds = Credentials(username=username, password=password)
# use one of the below config lines, depending on your usecase
config = Configuration(
service_endpoint='https://mobile.your_company.com/EWS/Exchange.asmx', credentials=creds, auth_type='NTLM')
# config = Configuration(server='outlook.office365.com', credentials=creds)
BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter
return Account(primary_smtp_address=email, autodiscover=False, config=config, access_type=DELEGATE)
def authenticate(email, password):
username = email
account = connect(email, username, password)
return account
def email_api(subject, body, to_list, cc_list = [], bcc_list= [], attachment_path = "", sender_email = "default_email", sender_password = "default_email_password"):
account = authenticate(sender_email, sender_password)
send_email(account, subject=subject, body = body, to = to_list, cc = cc_list, bcc= bcc_list, attachment_path = attachment_path)
email_api(subject = "Sub", body = "body", to_list = ["test@test.com"],
cc_list = ["test@test.com"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment