发送电子邮件与python [英] Send email with python
本文介绍了发送电子邮件与python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试创建一个简单的python脚本,发送一封电子邮件。我使用以下代码:
import subprocess
params = {'from':'from @ example.com',
'to':'to@example.com',
'subject':'Message subject'}
message ='''From:% (从)s
到:%(to)s
主题:%(subject)s
消息体
'''%params
sendmail = subprocess.Popen(['/ usr / share / sendmail',params ['to']]
sendmail.communicate(message)
但是,当我尝试运行它时,我会收到以下错误消息:
追溯(最近的最后一次呼叫):
文件/home/me/test.py,第15行,在< module>
sendmail = subprocess.Popen(['/ usr / share / sendmail',params ['to']]
文件/usr/lib/python2.7/subprocess.py,第679行,__init__
errread,errwrite)
文件/usr/lib/python2.7/subprocess.py,第1249行,在_execute_child
raise child_exception
OSError:[Errno 13]权限被拒绝
任何人都知道这个问题的解决方案,或者更好的代码? >
谢谢!
解决方案
而不是调用一个特定的过程,如果你邮件配置直接使用专用邮件库:
import smtplib
from email.mime.text import MIMEText
fp = open(textfile,'rb')
#创建一个文本/纯文本
msg = MIMEText(fp.read())
fp.close()
#格式标题
msg ['Subject'] ='我的主题'
msg ['From'] ='from@from.fr'
msg [ 'to'] ='to@to.com'
#发送消息通过米其林SMTP服务器,但不包括信封头。
s = smtplib.SMTP('您的邮件服务器')
s.sendmail('from@from.fr',['to@to.com'],msg.as_string())
s.quit()
你有更多的 python电子邮件示例。
I am trying to create a simple python script which sends an email. I used this following code:
import subprocess
params = {'from': 'from@example.com',
'to': 'to@example.com',
'subject': 'Message subject'}
message = '''From: %(from)s
To: %(to)s
Subject: %(subject)s
Message body
''' % params
sendmail = subprocess.Popen(['/usr/share/sendmail', params['to']])
sendmail.communicate(message)
But i recive the following error message when i try to run it:
Traceback (most recent call last):
File "/home/me/test.py", line 15, in <module>
sendmail = subprocess.Popen(['/usr/share/sendmail', params['to']])
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 13] Permission denied
Anyone knows a solution to this problem, or maybe a better code?
Thanks!
解决方案
Instead of calling a specific process, you can if your mail is configured directly use the dedicated mail libs:
import smtplib
from email.mime.text import MIMEText
fp = open(textfile, 'rb')
# Create a text/plain message
msg = MIMEText(fp.read())
fp.close()
# Format headers
msg['Subject'] = 'My subject'
msg['From'] = 'from@from.fr'
msg['To'] = 'to@to.com'
# Send the message via Michelin SMTP server, but don't include the envelope header.
s = smtplib.SMTP('your mail server')
s.sendmail('from@from.fr', ['to@to.com'], msg.as_string())
s.quit()
You have more python email examples in the doc.
这篇关于发送电子邮件与python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文