【问题标题】:Python SMTP Function Issue [closed]Python SMTP函数问题[关闭]
【发布时间】:2023-03-24 08:54:01
【问题描述】:

我有一个 python 脚本通过如下所示的 Gmail SMTP 设置发送电子邮件,它工作正常。但是,当我尝试将其转换为功能时,它不再发送任何电子邮件。您能给我的任何帮助将不胜感激。

import smtplib

SMTP_SERVER = 'smtp.gmail.com'
SMTP_PORT = 587

sender = 'account@gmail.com'
password = 'password'
recipient = ['user@Email1.com', 'user@Email2.com']
subject = 'Gmail SMTP Test'
body = 'blah blah blah'

body = "" + body + ""

headers = ["From: " + sender,
       "Subject: " + subject,
       "To: " + ", " .join(recipient),
       "MIME-Version: 1.0",
       "Content-Type: text/html"]
headers = "\r\n".join(headers)

session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)

session.ehlo()
session.starttls()
session.ehlo
session.login(sender, password)

session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
session.quit()

如果我尝试将其包装到一个函数中,它将不再发送电子邮件。我在 def SendEmail() 上尝试了几种不同的变体,但都没有运气。

import smtplib

def SendEmail(self): 
    SMTP_SERVER = 'account.gmail.com'
    SMTP_PORT = 587

    sender = 'account@gmail.com'
    password = 'Password'
    recipient = ['user@Email1.com', 'user@Email2.com']
    subject = 'Gmail SMTP Test'
    body = 'blah blah blah'

    body = "" + body + ""

    headers = ["From: " + sender,
           "Subject: " + subject,
           "To: " + ", " .join(recipient),
           "MIME-Version: 1.0",
           "Content-Type: text/html"]
    headers = "\r\n".join(headers)

    session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)

    session.ehlo()
    session.starttls()
    session.ehlo
    session.login(sender, password)

    session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
    session.quit()

【问题讨论】:

  • SMTP_SERVER不应该是smtp.gmail.com吗?

标签: python function smtplib


【解决方案1】:

你忘了调用一个函数。另外,您不需要self 参数:

import smtplib

def SendEmail():
    SMTP_SERVER = 'account.gmail.com'
    SMTP_PORT = 587

    sender = 'account@gmail.com'
    password = 'Password'
    recipient = ['user@Email1.com', 'user@Email2.com']
    subject = 'Gmail SMTP Test'
    body = 'blah blah blah'

    body = "" + body + ""

    headers = ["From: " + sender,
           "Subject: " + subject,
           "To: " + ", " .join(recipient),
           "MIME-Version: 1.0",
           "Content-Type: text/html"]
    headers = "\r\n".join(headers)

    session = smtplib.SMTP(SMTP_SERVER, SMTP_PORT)

    session.ehlo()
    session.starttls()
    session.ehlo
    session.login(sender, password)

    session.sendmail(sender, recipient, headers + "\r\n\r\n" + body)
    session.quit()

SendEmail()

另外,将SMTP_SERVER 之类的常量移到单独的配置文件中或者只是移出函数可能是个好主意。另外,如果您将 recipientsubjectbody 变量作为函数参数而不是在函数中硬编码它们,看起来会更好。

另外,session.ehlo(无括号)行什么也不做。

【讨论】:

    猜你喜欢
    • 2022-01-07
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 2014-11-20
    • 1970-01-01
    相关资源
    最近更新 更多