Python Forum
Send Error when attaching files
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Send Error when attaching files
#1
I’m encountering a sending error when trying to attach one or more files to an email using Python 3.

The script works perfectly with embedded images, styled text,…etc. It’s the block of code below that makes it fail if a document is listed. In this example, the file does exist (in this case on the Mac Desktop) and the path is correct. The script runs to conclusion and appears to send the email but the email fails to go through. If I omit this block, the email goes through with any included images, so the whole issue appears to be here.

The document name and path is provided in a variable and it may be one, none or several attachments in the variable.

The script runs completely but shows Sending Error when completed IF a file attachment was included.

#Attach Any Files     
    files = '''/Users/Me/Desktop/Document.pdf'''
    for file in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(file,"rb").read() )
        encoders.encode_base6[python]
4(part)
part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(file)))
msg.attach(part)[/python]
Reply
#2
You want to do this:
#Attach Any Files     
    files = ['/Users/Me/Desktop/Document.pdf']
    for file in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(file,"rb").read() )
        encoders.encode_base6[python]
Your code was trying to send files named '/', 'U', 's', 'e', 'r', 's'.... If you doubt me, try this:
for file in '''/Users/Me/Desktop/Document.pdf''':
    print(file)
Save triple quotes for multi-line quotes and docstrings, or when you have a string that contains quotes. It is odd seeing them used to quote a short string like this. It also odd seeing different quotes used for 'application' and "octet-stream". Pick a favorite quote character and use that for most strings. It makes your code easier to read.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  My journey with attaching file instead of images using Python numbnumb54 1 1,793 Jul-24-2020, 02:37 AM
Last Post: scidam
  How to send an error message Ewilliam51 1 2,066 Feb-15-2020, 08:41 AM
Last Post: ndc85430
  Attaching File tomthirteen 2 1,979 Dec-17-2018, 10:23 PM
Last Post: tomthirteen
  How can I send error message to slack using webhook url in Python? PrateekG 2 3,664 Jul-19-2018, 07:42 AM
Last Post: PrateekG
  Send and receive Files(data/images) betwenn a python app and another appl Akhou 2 3,952 May-02-2018, 08:20 AM
Last Post: Akhou
  PYTHON - send email with attachment Error PYTHONDUDE 1 3,994 Feb-27-2018, 07:52 PM
Last Post: PYTHONDUDE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020