简体   繁体   English

在 Python 中制作电子邮件功能

[英]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.看到这是您的两个片段中唯一真正的区别,这是我对出了什么问题的最佳想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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