0
  1. I am attempting to run a python script that automates sending emails with attachments

Here's the code

import smtplib
from email.mime.multipart import MIMEMultipart 
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders 


def gmail_login(username, password):
    smtp_server_name = "smtp.gmail.com"
    port_number = 587
    server = smtplib.SMTP(host=smtp_server_name, port=port_number)
    server.connect(host=smtp_server_name, port=port_number)
    server.starttls()
    server.login(user=username, password=password)
    return server

msg = MIMEMultipart()
msg['Subject'] = "Test Mail"
msg['From'] = 'myemail@gmail.com'
msg['To'] = 'email@gmail.com'
msg['Bcc'] = ''

#Create mail body message for email 

body ="""
Dear All, <br><br> Please find attachment 
"""

msg.attach(MIMEText(body, 'html'))

#Create Attachment 

file_path = ("C:\Users\thisuser\Desktop\FinalDetection\detections2.csv")
file_name = "detections2.csv"
file = open(file_path+"\\"+file_name, "rb")

payload = MIMEBase('application', 'octet-stream')
payload.set_payload(file.read())
file.close()
encoders.encode_base_base64(payload)
payload.add_header('Content_Disposition', 'attachment', filename=file_name)
msg.attach(payload)

server = gmail_login(username='myemail@gmail.com', password='password')
server.send_message(msg)
server.quit()
print("Email has been sent with an attachment")

Here's the error I receive

SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX

Any help is appreciated greatly.

Nick Perry
  • 11
  • 1
  • To put a \ inside a string in Python, you need to use \\. You need `"c:\\Users\\thisuser\\Desktop\\FinalDetection\\detections2.csv"` – Frank Yellin Mar 28 '22 at 23:56

0 Answers0