我遇到问题,当我的程序发送电子邮件时,我的电子邮件的主题部分会显示出来。我以为我遵循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')
答案 0 :(得分:1)
不确定您的代码有什么问题。
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
答案 1 :(得分:0)
尝试http://docs.python.org/library/email-examples.html中的示例 或者给我的示例代码一个。我不需要头文件,但我猜你可以添加它。如果你想要的话。
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)