I know this has been asked multiple times, but I can't seem to find a solution for my situation. I'm trying to send a text file from my computer through gmail. Many of y'all use email.MIMEMultipar
, but I find this complicated, so I use EmailMessage
. The email is sent properly, but instead of sending that text file, it creates another text file. In my code, I use msg.add_attachment("This is the file contents", filename="keyLog.txt")
for my text file. It creates another text file, with the message "This is the file contents". Is there some way to send the actual text file? Here's my code:
import smtplib, ssl
from email.message import EmailMessage
password = input("Type your password and press enter: ")
# Send email here
msg = EmailMessage()
msg["from"] = "example@gmail.com"
msg["Subject"] = "Subject"
msg["To"] = "example@gmail.com"
msg.set_content("This is the message body")
msg.add_attachment("This is the file contents", filename="keyLog.txt")
context=ssl.create_default_context()
with smtplib.SMTP("smtp.gmail.com", port=587) as smtp:
smtp.starttls(context=context)
smtp.login(msg["From"], password)
smtp.send_message(msg)
If it helps, the text file should say "Hello World". Thanks!