-1

I’m encountering a sending error when trying to attach one or more files to an email using Python 3.

The script works 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.

The script ends with except: print(msg.as_string()), which shows Sending Error.

#Attach Any Files     
if '''/Users/Me/Desktop/Document.pdf''' != "":
    files = '''/Users/Me/Desktop/Document.pdf'''
    for file in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(file,"rb").read() )
        encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="{0}"'.format(os.path.basename(file)))
        msg.attach(part)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
JAC
  • 1,061
  • 1
  • 10
  • 15
  • `for file in files`? `files` is a string. – wjandrea Aug 07 '23 at 16:26
  • did you mean to use `glob.glob(files)`? – ti7 Aug 07 '23 at 16:27
  • 1
    Maybe this is beside the point, but [a bare `except` is bad practice](/q/54948548/4518341). Instead, use the specific exception you're expecting like `except ValueError`, or at least `except Exception`. – wjandrea Aug 07 '23 at 16:27
  • @ti7 Why glob? It doesn't have any wildcards. – wjandrea Aug 07 '23 at 16:27
  • Also, why are you doing `if '''/Users/Me/Desktop/Document.pdf''' != "":`? A non-empty string literal by definition can't be equal to the empty string, so why bother? – wjandrea Aug 07 '23 at 16:28
  • There be one, none, or several attachments being provided via a variable, thus the if. In trying to convert it to post here I probably misrepresented that part. From the ```for file in files``` on, the script borrows exactly from several sources on the web, including on StackOverflow: https://stackoverflow.com/questions/26582811/gmail-python-multiple-attachments – JAC Aug 07 '23 at 17:25

0 Answers0