Sending Email Using exchangelib in Python
Pada posting kali ini penulis akan membahas tentang "Sending Email Using exchangelib in Python". Jika kita menggunakan exchanger server sebagai media untuk mengirimkan email maka kita perlu melakukan install 2 package dibawah ini.
exchangelib ==1.9.5
cryptography== 2.8
Jika kita menggunakan GMail untuk mengirim email maka kita biasanya menggunakan package smtplib. Tetapi jika menggunakan exchange server maka exchangelib lebih cocok.
Siapkan sebuah file config.ini dengan isi sbb :
[DEFAULT]
recipients = name1@domain.com, name2@domain.com
subject = Subject
Kemudian buatlah file python sbb :
#Exchange server
from exchangelib import DELEGATE,IMPERSONATION,Account,Credentials,ServiceAccount
from exchangelib import EWSDateTime,EWSTimeZone,Configuration,NTLM,CalendarItem,Message
from exchangelib import Mailbox,Attendee,Q,ExtendedProperty,FileAttachment,ItemAttachment
from exchangelib import HTMLBody,Build,Version
#Both
import os
import time
import configparser
from datetime import datetime, timedelta
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_mail_outlook(body):
print("Authenticating mail")
config = configparser.ConfigParser()
filename = os.getcwd() + r'\config.ini'
print(filename)
config.read(filename)
try:
msg = MIMEMultipart()
# setup the parameters of the message
msg['From'] = 'cs@domain.com'
msg['To'] = config['DEFAULT']['recipients']
msg['Subject'] = config['DEFAULT']['subject']
svr = 'www.server.com'
pwd = 'secret'
acc = r'DOMAIN\yourname'
creden = ServiceAccount(username = acc, password = pwd)
config = Configuration(server = svr, credentials = creden)
account = Account(primary_smtp_address = msg['From'],
config = config, autodiscover = False,
access_type = DELEGATE)
to_recipients = []
for item in msg['To'].split(","):
print('Adding recipient', item)
to_recipients.append(Mailbox(email_address = item))
print("Sending mail ....")
#create message
m = Message(account = account, folder = account.sent,
subject = 'Subject Email',
body = HTMLBody(body),
to_recipients = to_recipients)
#send message
m.send_and_save()
print("Sending Completed")
except Exception as exc:
print("Error ", exc)
pass
if __name__ == "__main__":
try:
html = "Email Content"
send_mail_outlook(html)
print("")
except Exception as error :
print(error)
finally:
if(connection):
cursor.close()
connection.close()
Semoga posting tentang "Sending Email Using exchangelib in Python" diatas dapat bermanfaat.
Salam,
Packages
exchangelib ==1.9.5
cryptography== 2.8
Jika kita menggunakan GMail untuk mengirim email maka kita biasanya menggunakan package smtplib. Tetapi jika menggunakan exchange server maka exchangelib lebih cocok.
Sample Script
Dibawah ini adalah sample script mengirimkan email dalam format HTML menggunakan exchange server.Siapkan sebuah file config.ini dengan isi sbb :
[DEFAULT]
recipients = name1@domain.com, name2@domain.com
subject = Subject
Kemudian buatlah file python sbb :
#Exchange server
from exchangelib import DELEGATE,IMPERSONATION,Account,Credentials,ServiceAccount
from exchangelib import EWSDateTime,EWSTimeZone,Configuration,NTLM,CalendarItem,Message
from exchangelib import Mailbox,Attendee,Q,ExtendedProperty,FileAttachment,ItemAttachment
from exchangelib import HTMLBody,Build,Version
#Both
import os
import time
import configparser
from datetime import datetime, timedelta
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
def send_mail_outlook(body):
print("Authenticating mail")
config = configparser.ConfigParser()
filename = os.getcwd() + r'\config.ini'
print(filename)
config.read(filename)
try:
msg = MIMEMultipart()
# setup the parameters of the message
msg['From'] = 'cs@domain.com'
msg['To'] = config['DEFAULT']['recipients']
msg['Subject'] = config['DEFAULT']['subject']
svr = 'www.server.com'
pwd = 'secret'
acc = r'DOMAIN\yourname'
creden = ServiceAccount(username = acc, password = pwd)
config = Configuration(server = svr, credentials = creden)
account = Account(primary_smtp_address = msg['From'],
config = config, autodiscover = False,
access_type = DELEGATE)
to_recipients = []
for item in msg['To'].split(","):
print('Adding recipient', item)
to_recipients.append(Mailbox(email_address = item))
print("Sending mail ....")
#create message
m = Message(account = account, folder = account.sent,
subject = 'Subject Email',
body = HTMLBody(body),
to_recipients = to_recipients)
#send message
m.send_and_save()
print("Sending Completed")
except Exception as exc:
print("Error ", exc)
pass
if __name__ == "__main__":
try:
html = "Email Content"
send_mail_outlook(html)
print("")
except Exception as error :
print(error)
finally:
if(connection):
cursor.close()
connection.close()
Semoga posting tentang "Sending Email Using exchangelib in Python" diatas dapat bermanfaat.
Salam,