Try to search your question here, if you can't find : Ask Any Question Now ?

How to specify remote file attachment for SMTP mail in Python

HomeCategory: stackoverflowHow to specify remote file attachment for SMTP mail in Python
Avatarrupesh asked 4 weeks ago

How can the remote attachment file be specified to be included in SMTP mail? Attachement file is located on different server (own username/password access)

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
mail_content = """ This is body content """

sender_addr = "sender_addr@server.com"
sender_pass = "apassword"
receiver_addr = "receiver_addr@server.com"

# Create MIME header
msg = MIMEMultipart()
msg['From'] = sender_addr
msg['To'] = receiver_addr
msg['Subject'] = 'A test mail subject sent by Python'
msg.attach(MIMEText(mail_content, 'plain'))

fname = "doc_1.pdf"
attach_file = open(fname, 'rb')  # **<- How can I specify the remote path here?**
payload = MIMEBase('application', 'octet-stream')
# Attach an attachment to payload
payload.set_payload((attach_file).read())
encoders.encode_base64(payload)  

# Add payload header with filename
payload.add_header('Content-Disposition', 'attachment', filename=fname)
msg.attach(payload)

# Create SMTP client
client = smtplib.SMTP('smtp.gmail.com', 587) 
client.starttls()                              
client.login(sender_addr, sender_pass)      
text = msg.as_string()                     

client.sendmail(sender_addr, receiver_addr, text)
client.quit()
print('Mail sent!')
1 Answers
Best Answer
AvatarMikhail answered 4 weeks ago
Your Answer

3 + 15 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com