Mar-06-2022, 08:02 PM
(This post was last modified: Mar-06-2022, 08:02 PM by cosmarchy.
Edit Reason: Change to provide clarity
)
Hi,
I'm trying to end email attachments and have written the following:
When I run this with the attachment (second to last line) I get the following:
If someone could assist with this why the attachment part of the code produces an error please, I would appreciate it.
Thanks
I'm trying to end email attachments and have written the following:
import os
import smtplib
import random
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import encoders
from os.path import basename
from email.mime.application import MIMEApplication
from email.utils import COMMASPACE, formatdate
def send_mail(send_from, send_to, subject, text, files=None):
msg = MIMEText(text)
msg['From'] = send_from
msg['To'] = COMMASPACE.join(send_to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
if isinstance(files, list):
msg = MIMEMultipart()
for f in files or []:
with open(f, "rb") as fil:
part = MIMEApplication(fil.read(),Name=basename(f))
part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
msg.attach(part)
try:
server = smtplib.SMTP_SSL('smtp.pobox.com', 465)
server.ehlo()
server.login("<email address>", "<password>")
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.close()
print ("successfully sent the mail")
except:
print ("failed to send mail")
send_mail("<email address>",[<email address>],"subject","text",["D:\\Desktop\\Python Test\\Logfile.txt"]) # with attachment
#send_mail("<email address>",[<email address>],"subject","text") # without attachmentthe idea being that I can use the same function whether I want to send an email with or without an attachment - all I have to do is leave the attachment argument empty...When I run this with the attachment (second to last line) I get the following:
Output:PS D:\Desktop\Python Test> & C:/Users/me/AppData/Local/Programs/Python/Python39/python.exe "d:/Desktop/Python Test/SendEmail2.py"
failed to send mailbut when I send email without attachment (last line) I get the following:Output:PS D:\Desktop\Python Test> & C:/Users/me/AppData/Local/Programs/Python/Python39/python.exe "d:/Desktop/Python Test/SendEmail2.py"
successfully sent the mailSo, I can rule out login issues as appears to work when not sending attachments.If someone could assist with this why the attachment part of the code produces an error please, I would appreciate it.
Thanks
