Python发送简单邮件
Python send simple mail
我正在尝试编写一个在某些情况下必须发送简单电子邮件的简单脚本。
我有以下脚本,如果我只使用这个脚本,它运行良好。
import smtplib
mail_user = '123@123.com'
mail_password = 'password'
sent_from = mail_user
to = ['reciever@address.com']
subject = 'My subject'
body = 'Hello mail.'
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
server = smtplib.SMTP_SSL('mail.123.com', 465)
server.ehlo()
server.login(mail_user, mail_password)
server.sendmail(sent_from, to, email_text)
server.close()
print 'Email sent!'
except:
print 'Something went wrong...'
问题是当我试图将此代码放入 def 并从 e-mail 外部调用时丢失 headers,我的意思是电子邮件到达时没有发件人也没有主题。发件人为空,主题为空,但我只有 body。
当我发送到另一个域时我也无法收到邮件,但我认为这是因为另一个域在没有 headers 的情况下拒绝邮件,当仅使用脚本时邮件也会到达其他域。
import smtplib
def sendMail():
mail_user = '123@123.com'
mail_password = 'password'
sent_from = mail_user
to = ['reciever@address.com']
subject = 'My subject'
body = 'Hello mail.'
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
server = smtplib.SMTP_SSL('mail.123.com', 465)
server.ehlo()
server.login(mail_user, mail_password)
server.sendmail(sent_from, to, email_text)
server.close()
print 'Email sent!'
except:
print 'Something went wrong...'
sendMail();
当我将这段代码放入 def 时有什么区别?为什么会这样?我做错了什么?
感谢您的帮助。
def sendMail():
调用它:
sendMail()
不是 SendMail()
在您的函数版本中,您的电子邮件 headers 已 缩进
email_text = """\
From: %s
To: %s
Subject: %s
%s
...
在此字符串中,To:
和 Subject:
现在缩进了。
我正在尝试编写一个在某些情况下必须发送简单电子邮件的简单脚本。 我有以下脚本,如果我只使用这个脚本,它运行良好。
import smtplib
mail_user = '123@123.com'
mail_password = 'password'
sent_from = mail_user
to = ['reciever@address.com']
subject = 'My subject'
body = 'Hello mail.'
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
server = smtplib.SMTP_SSL('mail.123.com', 465)
server.ehlo()
server.login(mail_user, mail_password)
server.sendmail(sent_from, to, email_text)
server.close()
print 'Email sent!'
except:
print 'Something went wrong...'
问题是当我试图将此代码放入 def 并从 e-mail 外部调用时丢失 headers,我的意思是电子邮件到达时没有发件人也没有主题。发件人为空,主题为空,但我只有 body。 当我发送到另一个域时我也无法收到邮件,但我认为这是因为另一个域在没有 headers 的情况下拒绝邮件,当仅使用脚本时邮件也会到达其他域。
import smtplib
def sendMail():
mail_user = '123@123.com'
mail_password = 'password'
sent_from = mail_user
to = ['reciever@address.com']
subject = 'My subject'
body = 'Hello mail.'
email_text = """\
From: %s
To: %s
Subject: %s
%s
""" % (sent_from, ", ".join(to), subject, body)
try:
server = smtplib.SMTP_SSL('mail.123.com', 465)
server.ehlo()
server.login(mail_user, mail_password)
server.sendmail(sent_from, to, email_text)
server.close()
print 'Email sent!'
except:
print 'Something went wrong...'
sendMail();
当我将这段代码放入 def 时有什么区别?为什么会这样?我做错了什么?
感谢您的帮助。
def sendMail():
调用它:
sendMail()
不是 SendMail()
在您的函数版本中,您的电子邮件 headers 已 缩进
email_text = """\
From: %s
To: %s
Subject: %s
%s
...
在此字符串中,To:
和 Subject:
现在缩进了。