**UPDATE2:在 V2 的最后一段代码中,我smtp.sendmail(email_address, address, msg,)
与smtp.sendmail(email_address, phone_book, msg,)
直接访问 phone_book 交换似乎已经解决了这个问题。这是任何正在寻找的人的工作代码:
import smtplib
email_address = '' # Your email goes here
email_password = '' # Your password goes here
phone_book = [''] # List of receivers
def Add_Email():
client_email = input('Email of receiver? ')
phone_book.append(client_email)
def Add_Subject_Message_Send():
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(email_address, email_password)
subject = input('Enter your subject here: ')
body = input('Enter your message here: ')
msg = f'Subject: {subject}\n\n{body}'
for i in phone_book:
address = i
smtp.sendmail(email_address, phone_book, msg,)
Add_Email()
Add_Subject_Message_Send()
**
**更新:我用没有 GUI 的最简单版本交换了代码。当主题和主体在代码中定义时,V1 工作。当用户定义主题和正文时,V2 不起作用。现在 V2 有这个错误信息:
Traceback (most recent call last):
File "c:/Users/Me/Desktop/work/infosend/test4.py", line 33, in <module>
Add_Subject_Message_Send()
File "c:/Users/Me/Desktop/work/infosend/test4.py", line 29, in Add_Subject_Message_Send
smtp.sendmail(email_address, address, msg,)
File "C:\python\lib\smtplib.py", line 885, in sendmail
raise SMTPRecipientsRefused(senderrs)
smtplib.SMTPRecipientsRefused: {'': (555, b'5.5.2 Syntax error. l15sm65056407wrv.39 - gsmtp')}
**
我正在使用 smtplib 发送电子邮件。只要在代码中定义了消息的主题和正文,一切都会正常工作并且电子邮件会被传递。当代码中没有定义主题或正文时,不会显示错误,但不会传递消息。
我想创建一个函数,允许我编写主题和消息是什么,而不是在代码中定义它。我的功能似乎工作,但没有消息被传递,也没有收到错误消息。
附上我的代码的两个版本。
第一个版本有效。它定义了主体和主体。
第二版不行。包括定义主题和主体的功能。终端没有收到错误。
V1
import smtplib
email_address = '' # Enter your email address here
email_password = '' # Enter your email password here
phone_book = [''] # Here enter the email of receiver
with smtplib.SMTP('smtp.gmail.com', 587) as smtp: # Connects with GMAIL
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(email_address, email_password)
subject = 'test3' # Subject and body defined in code = works
body = 'test3'
msg = f'Subject: {subject}\n\n{body}'
for i in phone_book:
address = i
smtp.sendmail(email_address, address, msg,)
V2
import smtplib
email_address = '' # Your email goes here
email_password = '' # Your password goes here
phone_book = [''] # List of receivers
def Add_Email():
client_email = input('Email of receiver? ')
phone_book.append(client_email)
def Add_Subject_Message_Send():
with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(email_address, email_password)
subject = input('Enter your subject here: ')
body = input('Enter your message here: ')
msg = f'Subject: {subject}\n\n{body}'
for i in phone_book:
address = i
smtp.sendmail(email_address, address, msg,)
Add_Email()
Add_Subject_Message_Send()