[英]Sending email subject in Python
我在程序发送电子邮件时出现问题,无法显示电子邮件的主题部分。 我以为我遵循的是SMTP的RFC规范。但是我似乎无法弄清楚我在做什么错。 任何帮助是极大的赞赏。
def email():
sender = 'username@domain.com'
receivers = ['username@domain.com']
message = """From: From Admin <admin@domain.com>
To:To Person <user@domain.com>
Subject: Important Information
This is a test email message.
"""
try:
smtpObj = smtplib.SMTP('domain.com', 25)
smtpObj.sendmail(sender, receivers, message)
print "Successfully sent email"
except smtplib.SMTPException:
print('Error: unable to send email')
不知道您的代码出了什么问题。
FWIW,我过去使用过string.join来创建我的消息正文:
def send_email():
import string,smtplib
SMTPserver = "smtp.com"
# To is a comma-separated list
To = "sender@domain.com"
From = "receipient@domain.com"
Subj = "test subject"
Text = """test email.
Not sure what the problem is
Multi-line anyway."""
Body = string.join((
"From: %s" % From,
"To: %s" % To,
"Subject: %s" % Subj,
"",
Text,
), "\r\n")
s = smtplib.SMTP(SMTPserver)
s.sendmail(From,[To],Body)
s.quit()
-J
从http://docs.python.org/library/email-examples.html尝试该示例,或者尝试一下我的示例代码。 我不需要from头,但是我想您可以根据需要添加它。
import smtplib
USER_NAME = 'username@domain.com'
PASSWORD = getpass.getpass("%s's PASSWORD: " % USER_NAME)
DEBUG = True
MESSAGE_FORMAT = "From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n%s" # %(fromAddr,to,subject,text)
def sendEmail(recipient,message):
SMTP_SERVER_URL = 'smtp.gmail.com'
mailserver = smtplib.SMTP(SMTP_SERVER_URL)
if DEBUG:
mailserver.set_debuglevel(1)
mailserver.ehlo()
mailserver.starttls()
mailserver.ehlo()
mailserver.login(USER_NAME,PASSWORD)
mailserver.sendmail('', recipient, message)
mailserver.close()
def sendEmailWithFields(to,subject,text):
message = MESSAGE_FORMAT%('', to, subject, text)
sendEmail(to,message)
if __name__ == '__main__':
to = 'receipient@domain.com'
subject = 'The subject'
text = 'The text body'
sendEmailWithFields(to,subject,text)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.