我无法使用 SMTLIB 添加主题 | Python
I can't add a subject with SMTLIB | Python
我和我的朋友一直在编写电子邮件发件人的代码,但如果您能帮忙,我们无法在电子邮件中发送主题;非常感谢:
import smtplib
def send_email(send_to, subject, message):
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login("*******", "******")
server.sendmail('******', send_to, message, subject)
server.quit()
target = input('Who are you sending the email to? ')
subj = input('What is your subject? ')
body = input('Enter the message you want to send: ')
send_email(target, subj, body)
except SMTPException:
print("Error: unable to send email")
对 smtplib.SMTP.sendmail()
的调用不带 subject
参数。有关如何调用它的说明,请参阅文档。
主题行以及所有其他 headers 作为消息的一部分包含在称为 RFC822 格式的格式中,位于最初定义该格式的 now-obsolete 文档之后。使您的消息符合该格式,如下所示:
import smtplib
fromx = 'xxx@gmail.com'
to = 'xxx@gmail.com'
subject = 'subject' #Line that causes trouble
msg = 'Subject:{}\n\nexample'.format(subject)
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.ehlo()
server.login('xxx@gmail.com', 'xxx')
server.sendmail(fromx, to, msg)
server.quit()
当然,使您的消息符合所有适当标准的更简单方法是使用 Python email.message
标准库,如下所示:
import smtplib
from email.mime.text import MIMEText
fromx = 'xxx@gmail.com'
to = 'xxx@gmail.com'
msg = MIMEText('example')
msg['Subject'] = 'subject'
msg['From'] = fromx
msg['To'] = to
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.ehlo()
server.login('xxx@gmail.com', 'xxx')
server.sendmail(fromx, to, msg.as_string())
server.quit()
还有其他例子。
我和我的朋友一直在编写电子邮件发件人的代码,但如果您能帮忙,我们无法在电子邮件中发送主题;非常感谢:
import smtplib
def send_email(send_to, subject, message):
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.login("*******", "******")
server.sendmail('******', send_to, message, subject)
server.quit()
target = input('Who are you sending the email to? ')
subj = input('What is your subject? ')
body = input('Enter the message you want to send: ')
send_email(target, subj, body)
except SMTPException:
print("Error: unable to send email")
对 smtplib.SMTP.sendmail()
的调用不带 subject
参数。有关如何调用它的说明,请参阅文档。
主题行以及所有其他 headers 作为消息的一部分包含在称为 RFC822 格式的格式中,位于最初定义该格式的 now-obsolete 文档之后。使您的消息符合该格式,如下所示:
import smtplib
fromx = 'xxx@gmail.com'
to = 'xxx@gmail.com'
subject = 'subject' #Line that causes trouble
msg = 'Subject:{}\n\nexample'.format(subject)
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.ehlo()
server.login('xxx@gmail.com', 'xxx')
server.sendmail(fromx, to, msg)
server.quit()
当然,使您的消息符合所有适当标准的更简单方法是使用 Python email.message
标准库,如下所示:
import smtplib
from email.mime.text import MIMEText
fromx = 'xxx@gmail.com'
to = 'xxx@gmail.com'
msg = MIMEText('example')
msg['Subject'] = 'subject'
msg['From'] = fromx
msg['To'] = to
server = smtplib.SMTP('smtp.gmail.com:587')
server.starttls()
server.ehlo()
server.login('xxx@gmail.com', 'xxx')
server.sendmail(fromx, to, msg.as_string())
server.quit()
还有其他例子。