Reputation: 436
I'm trying to send an HTML email, however, when I run this code, literally nothing happens. I sit and wait as the program never finishes. What did I do wrong?
import smtplib, ssl, getpass
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
port = 465
smtp_server = "smtp.gmail.com"
sender_email = "REDACTED"
receiver_email = "REDACTED"
password = getpass.getpass()
html = """
<html>
<head></head>
<body>
<h1>HEADER</h1>
<br>
body<br>
</body>
</html>
"""
msg = MIMEMultipart()
attach = MIMEText(html, 'html')
msg.attach(attach)
context = ssl.create_default_context()
with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, msg)
server.close()
Upvotes: 0
Views: 355
Reputation: 315
The msg needs to be flattened to a string before passing it to the sendmail method:
server.sendmail(sender_email, receiver_email, str(msg))
Also, you'll probably want to set some headers on the msg object:
msg.add_header('From', sender_email)
msg.add_header('Subject', 'whatever')
Enabling the debug output for the SMTP object would help to track down these problems, try inserting this line above the server.login call:
server.set_debuglevel(1)
If you're going to be working with email though it may be worth looking in to the email.message.EmailMessage class.
Upvotes: 1
Reputation: 264
I've found sending mail using gmails SMTP server hard and difficult to work out (The only way I have even gotten it to work is by using a temporary thing that lets me send emails through my email address and only works half the time)
Instead, I suggest sending your email through SendGrid, using their python API, or another service that offers a similar function (Not being biased just have used SendGrid before and found it very easy and reliable) and just send a request to that every time you want to send an email.
I know its a dodgy way to get it to work but its the only way I've been able to send emails through my Gmail account using python :)
(Id comment this as it isn't really an answer but a workaround however I don't have enough reputation)
Upvotes: 0