Python Forum

Full Version: Sending Attachments via smtplib [SOLVED]
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello everybody,

I have an E-Mail script written in python which sends notifications to my personal mail account.
Now I want to extend on that by adding an attachment (an image, the format doesn't matter) but I don't know how to do so.
Below you can see my code.

#!/usr/bin/env python3

import smtplib

f1 = open("../index/mail.txt","r")
mail = f1.read() [:-1]
f1.close()

f2 = open("../index/passwd.txt","r")
passwd = f2.read() [:-1]
f2.close()

f3 = open("../index/receiver.txt","r")
receiver = f3.read() [:-1]
f3.close()

#Email Variables
SMTP_SERVER = 'smtp.gmail.com'  #Email Server (don't change!)
SMTP_PORT = 587                 #Server Port (don't change!)
GMAIL_USERNAME = mail           #change this to match your gmail account
GMAIL_PASSWORD = passwd         #change this to match your gmail password
 
class Emailer:
    def sendmail(self, recipient, subject, content):
 
        #Create Headers
        headers = ["From: " + GMAIL_USERNAME, "Subject: " + subject, "To: " + recipient,
                   "MIME-Version: 1.0", "Content-Type: text/html"]
        headers = "\r\n".join(headers)
 
        #Connect to Gmail Server
        session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)
        session.ehlo()
        session.starttls()
        session.ehlo()
 
        #Login to Gmail
        session.login(GMAIL_USERNAME, GMAIL_PASSWORD)
 
        #Send Email & Exit
        msg = (headers + "\r\n\r\n" + content).encode('utf-8')
        session.sendmail(GMAIL_USERNAME, recipient, msg)
        session.quit
 
sender = Emailer()
 
sendTo = receiver
 
emailSubject = "Subject"
emailContent = "Content"
 
#Sends an email to the "sendTo" address with the specified "emailSubject" as the subject and "emailConten$
sender.sendmail(sendTo, emailSubject, emailContent)
If use yagmail it's easier.
Quick test works fine for me.
import yagmail

receiver = "[email protected]"
body = "Hello there from Yagmail"
filename = "test.pdf"

yag = yagmail.SMTP("[email protected]", pass-xxxx)
yag.send(
    to=receiver,
    subject="Python test with attachment",
    contents=body, 
    attachments=filename,
)
(Oct-27-2021, 11:35 PM)snippsat Wrote: [ -> ]If use yagmail it's easier.
Quick test works fine for me.
import yagmail

receiver = "[email protected]"
body = "Hello there from Yagmail"
filename = "test.pdf"

yag = yagmail.SMTP("[email protected]", pass-xxxx)
yag.send(
    to=receiver,
    subject="Python test with attachment",
    contents=body, 
    attachments=filename,
)

That worked fine, thank you.