Can someone help me send an email from my exchange account and add attachments. SMTP doesnt work, I get immediate timeout issues. 0365 doesn’t save a copy to my sent folder. The only other one I know is exchangelib
JavaScript
x
35
35
1
from exchangelib import Account, Credentials, Message, Mailbox, FileAttachment
2
from email.mime.multipart import MIMEMultipart
3
from email.mime.base import MIMEBase
4
from email.mime.text import MIMEText
5
from email.utils import formatdate
6
from email import encoders
7
8
email = 'XXXXXXXX'
9
password = 'XXXXXXXX'
10
11
a = Account(email, credentials=Credentials(email, password), autodiscover=True)
12
13
14
15
dir_path = ('C:/Users/Istcrmt/Documents/Python/PythonforAnaconda3.5/')
16
excel_name = 'test.xlsx'
17
18
#attach an excel file:
19
20
21
for i in email_list.itertuples():
22
# if you want a copy in the 'Sent' folder
23
m = Message(
24
account=a
25
,folder=a.sent
26
,subject=(i.AGENCY_NAME + ' I made an email script.')
27
,body='All bodies are beautiful'
28
,to_recipients=[Mailbox(email_address=i.NEW_MAIL)])
29
30
#attach files
31
m.attachments.append(part)
32
# m.attach(cover_letter)
33
34
m.send_and_save()
35
Advertisement
Answer
This is how you send emails with an attachment with exchangelib
:
JavaScript
1
58
58
1
from exchangelib import ServiceAccount, Configuration, Account, DELEGATE
2
from exchangelib import Message, Mailbox, FileAttachment
3
4
from config import cfg # load your credentials
5
6
7
def send_email(account, subject, body, recipients, attachments=None):
8
"""
9
Send an email.
10
11
Parameters
12
----------
13
account : Account object
14
subject : str
15
body : str
16
recipients : list of str
17
Each str is and email adress
18
attachments : list of tuples or None
19
(filename, binary contents)
20
21
Examples
22
--------
23
>>> send_email(account, 'Subject line', 'Hello!', ['info@example.com'])
24
"""
25
to_recipients = []
26
for recipient in recipients:
27
to_recipients.append(Mailbox(email_address=recipient))
28
# Create message
29
m = Message(account=account,
30
folder=account.sent,
31
subject=subject,
32
body=body,
33
to_recipients=to_recipients)
34
35
# attach files
36
for attachment_name, attachment_content in attachments or []:
37
file = FileAttachment(name=attachment_name, content=attachment_content)
38
m.attach(file)
39
m.send_and_save()
40
41
42
credentials = ServiceAccount(username=cfg['user'],
43
password=cfg['password'])
44
45
config = Configuration(server=cfg['server'], credentials=credentials)
46
account = Account(primary_smtp_address=cfg['smtp_address'], config=config,
47
autodiscover=False, access_type=DELEGATE)
48
49
# Read attachment
50
attachments = []
51
with open('filestorage/numbers-test-document.pdf', 'rb') as f:
52
content = f.read()
53
attachments.append(('whatever.pdf', content))
54
55
# Send email
56
send_email(account, 'Test 14:35', 'works', ['info@example.com'],
57
attachments=attachments)
58
Related: Read emails and download attachment from an Exchange Server