从Python发送电子邮件

时间:2017-12-29 08:45:52

标签: python python-3.x sendmail email-validation smtplib

我正在尝试使用smtp服务器从python发送电子邮件。但它会抛出 错误。我该如何解决? 我也获得了gmail的许可才能使用此功能 这是代码

{{1}}

此代码通过此错误     TypeError:send()接受2个位置参数,但是给出了4个

请修正此错误。

2 个答案:

答案 0 :(得分:4)

你应该使用

sendmail

smtplib.SMTP.sendmail(self, from_addr, to_addrs, msg, mail_options=[], rcpt_options=[])
  

此命令执行整个邮件事务。

     

参数是:

- from_addr    : The address sending this mail.
- to_addrs     : A list of addresses to send this mail to.  A bare
                 string will be treated as a list with 1 address.
- msg          : The message to send.
- mail_options : List of ESMTP options (such as 8bitmime) for the
                 mail command.
- rcpt_options : List of ESMTP options (such as DSN commands) for
                 all the rcpt commands.

答案 1 :(得分:1)

import smtplib 
import email
from email.MIMEMultipart import MIMEMultipart
from email.Utils import COMMASPACE
from email.MIMEBase import MIMEBase
from email.parser import Parser
from email.MIMEImage import MIMEImage
from email.MIMEText import MIMEText
from email.MIMEAudio import MIMEAudio
import mimetypes

def send(user, password, fromaddr, to, subject, body):
smtp_host = 'smtp.gmail.com'
smtp_port = 587
server = smtplib.SMTP()
server.connect(smtp_host,smtp_port)
server.ehlo()
server.starttls()
server.login(user, password)

msg = email.MIMEMultipart.MIMEMultipart()
msg['From'] = fromaddr
msg['To'] = email.Utils.COMMASPACE.join(to)
msg['Subject'] = subject
msg.attach(MIMEText(body))
server.sendmail(user,to,msg.as_string())