简体   繁体   中英

Making an email function in Python

I'm working on a project right now that requires the capability to send emails. My problem is that whenever I put the emailing code into a function, it stops working.

Here's the function (excluding the actual email and password information of course):

import smtplib, ssl

port = 465
smtp_server = "smtp.gmail.com"
sender_email = "my_email@gmail.com"
receiver_email = "their_email@gmail.com"
password = "password"
message = """\
    Subject: Subject

    This is the email body"""

def send(msg):

    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)
        print("SENT")

if __name__ == "__main__":
    send(message)

this doesn't even give me errors, it just doesn't work. However, if I do it like this, everything works fine:

import smtplib, ssl

port = 465
smtp_server = "smtp.gmail.com"
sender_email = "my_email@gmail.com"
receiver_email = "their_email@gmail.com"
password = "password"
message = """\
Subject: Subject

This is the email body"""

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, message)
    print("SENT")

Any thoughts on why this is happening?

The only difference I can see is the whitespace before your subject line in the email's contents. Try removing it such that your snippet is as follows:

import smtplib, ssl

port = 465
smtp_server = "smtp.gmail.com"
sender_email = "my_email@gmail.com"
receiver_email = "their_email@gmail.com"
password = "password"
message = """\
Subject: Subject

This is the email body"""

def send(msg):

    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)
        print("SENT")

if __name__ == "__main__":
    send(message)

Seeing as this is the only real difference in your two snippets, this is my best idea as to what is going wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM