使用python发送电子邮件

使用python发送电子邮件,python,email,send,Python,Email,Send,我试图创建一个简单的python脚本来发送电子邮件。我使用了以下代码: 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

我试图创建一个简单的python脚本来发送电子邮件。我使用了以下代码:

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)
但我在尝试运行时收到以下错误消息:

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
回溯(最近一次呼叫最后一次):
文件“/home/me/test.py”,第15行,在
sendmail=subprocess.Popen(['/usr/share/sendmail',params['to']]
文件“/usr/lib/python2.7/subprocess.py”,第679行,在__
错误读取,错误写入)
文件“/usr/lib/python2.7/subprocess.py”,第1249行,在执行子进程中
引发子对象异常
OSError:[Errno 13]权限被拒绝
有人知道这个问题的解决方案,或者更好的代码吗


谢谢

/usr/share/sendmail非常不寻常-您确定您的sendmail二进制文件确实存在吗?通常它位于
/usr/sbin/sendmail

如果我是你,我宁愿使用标准库,而不是直接给sendmail打电话

您可以这样使用它来发送消息:

 server = smtplib.SMTP('smtp.example.com')
 server.sendmail(fromaddr, toaddrs, msg)
 server.quit()

如果配置了邮件,您可以直接使用专用邮件库,而不是调用特定进程:

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()

文档中还有更多内容。

下面是一些使用smtplib发送电子邮件的代码,可以执行TLS/SSL

import smtplib
from email.MIMEText import MIMEText
from email.utils import parseaddr

class Mailer(object):
    def __init__(self, fromAddress, toAddress, password):
        self.fromAddress = parseaddr(fromAddress)[1]
        self.toAddress = parseaddr(toAddress)[1]
        self.password = password

    def send(self, subject, body):
        msg = MIMEText(body)
        msg["From"] = self.fromAddress
        msg["Reply-to"] = self.toAddress
        msg["To"] = self.toAddress
        msg["Subject"] = subject

        sender = msg["From"]
        recipient = msg["To"]

        messageText = "".join(str(msg))
        mxhost = self.lookup(sender) # lookup finds the host that you want to send to

        server = smtplib.SMTP(mxhost, 587) #port 465 or 587
        server.ehlo()
        server.starttls()
        server.ehlo()
        server.login(sender, self.password)
        server.sendmail(sender, recipient, messageText)
        server.close()

这是我发送电子邮件的代码

#coding: utf-8

import smtplib
from email.mime.text import MIMEText
from email.utils import formatdate

def send_mail(to_list,sub,content):
    mail_host="smtp.example.com"
    mail_user="nvi"
    mail_pass="password"
    mail_postfix="example.com"
    me=mail_user + '555' +"<"+mail_user+"@"+mail_postfix+">"
    msg = MIMEText(content, _subtype='plain', _charset='utf-8')
    msg['Subject'] = sub
    msg['From'] = me
    msg['To'] = to_list
    msg['Date'] = formatdate(localtime=True)
    msg['Bcc'] = '123@example.com'
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(me, to_list, msg.as_string())
        s.close()
        return True
    except Exception, e:
        print e
        return False


if __name__ == "__main__":
    send_mail('my_email_address', 'subject', 'content')
#编码:utf-8
导入smtplib
从email.mime.text导入MIMEText
从email.utils导入格式日期
def发送邮件(收件人列表、子列表、内容):
mail\u host=“smtp.example.com”
mail_user=“nvi”
mail_pass=“密码”
mail\u postfix=“example.com”
me=邮件用户+'555'+“”
msg=MIMEText(内容,_subtype='plain',_charset='utf-8')
msg['Subject']=sub
msg['From']=我
msg['To']=收件人列表
msg['Date']=formattate(localtime=True)
msg['Bcc']='123@example.com'
尝试:
s=smtplib.SMTP()
s、 连接(邮件主机)
s、 登录(邮件用户、邮件通行证)
s、 sendmail(我,收件人列表,msg.as\u string())
s、 关闭()
返回真值
除例外情况外,e:
打印e
返回错误
如果名称=“\uuuuu main\uuuuuuuu”:
发送邮件(“我的电子邮件地址”、“主题”、“内容”)

我的程序与gMail配合使用,你可以尝试使用它来处理其他任何事情。你也可以发送短信。我在下面附上我的代码

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
Type = input("Enter 1 for eMail, 2 for SMS: ")
toaddr = 0
if Type=='1':
   toaddr = input("Enter to address: ")
else:
   Provider = input("1 for Sprint, 2 for AT&T, and 3 for Verizon: ")
   Mobile = input("Enter the mobile number: ")
   if Provider=='1': 
      toaddr = str(Mobile) + "@messaging.sprintpcs.com"
   if Provider=='2':
      toaddr = str(Mobile) + '@txt.att.net'
   if Provider=='3':
      toaddr = str(Mobile) + ''
   print (toaddr)      
head = input("Enter your subject: ")
body = input("Enter your message: ")
fromaddr = input("Enter the 'From Address'(example@gmail.com): ")
msg = MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = toaddr
msg['Subject'] = head
password = input("Enter the from address password: ")
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login(fromaddr, password)
text = msg.as_string()
server.sendmail(fromaddr, toaddr, text)
server.quit()

我希望这会有所帮助。

您可以使用内置smtp库,而不是调用sendmail二进制文件。有什么特殊原因不使用python的
smtplib
email
模块吗?对我来说,它没有抛出上述错误。在我的系统中,sendmail位于/usr/sbin/sendmail中,只需在命令提示符下进行检查即可发送邮件。@guidot否,我没有特别的理由接受建议。@tuxudy我将其移动到/usr/sbin/sendmail,但没有结果:/i尝试运行它时收到以下错误消息:错误:[Errno 111]连接被拒绝。因此这是一个SMTP服务器配置错误。您是否尝试使用
'localhost'
作为服务器?我在终端中编写了whereis sendmail,它响应的是/usr/share/sendmail。但是我现在已经将sendmail文件夹移动到了/usr/sbin,并且给出了相同的errormsg。这已经脱离了主题,但是sendmail确实可以从命令行工作吗?