【问题标题】:Sending email from Python从 Python 发送电子邮件
【发布时间】:2018-06-09 17:34:08
【问题描述】:

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

import smtplib


content='Hello I am just checking email.'
mail=smtplib.SMTP('smtp.gmail.com',587)
mail.ehlo()
mail.starttls()
mail.login('My email','Mypassword')
mail.send('From email','destiation password',content)
mail.close()

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

请修正这个错误。

【问题讨论】:

  • 试试sendmail而不是send

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


【解决方案1】:

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.

【讨论】:

    【解决方案2】:
    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())
    

    【讨论】:

      猜你喜欢
      • 2022-10-13
      • 2016-04-09
      • 2018-01-25
      • 2020-11-03
      • 2015-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多