【问题标题】:How send an emai only by smtplib in python 3-x [duplicate]如何在 python 3-x 中仅通过 smtplib 发送电子邮件 [重复]
【发布时间】:2021-07-10 13:57:44
【问题描述】:

我想通过 smtplib 发送电子邮件,但它给了我错误

    server.send_message(user_name, to, message, subject=subject)
TypeError: send_message() got an unexpected keyword argument 'subject'

这段代码

    import smtplib
    user_name = 'my@gmail.com'
    password = '*******'
    to = ['my@gmail.com', 'other_email@gmail.com']
    subject = 'Theme'
    message = 'Test message'
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(user_name, password)
    server.send_message(user_name, to, message, subject=subject)
    server.close()

我尝试从代码中删除主题,但它给了我新的错误

      File "C:\\lib\smtplib.py", line 939, in send_message
        resent = msg.get_all('Resent-Date')
    AttributeError: 'str' object has no attribute 'get_all'

我该如何解决这个问题?

编辑:

我找到了怎么做的

import smtplib

gmail_user = 'my_gmail@gmail.com' #like boris273@gmail.com
gmail_password = 'password'

sent_from = gmail_user
to = ['email@gmail.com', 'email@gmail.com'] #Some emails to which your message will be sent
subject = input('Subject > ')
body = input('Message > ')
email_text = """\
From: %s
To: %s
Subject: %s

%s
""" % (sent_from, ", ".join(to), subject, body)

try:
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(gmail_user, gmail_password)
    server.sendmail(sent_from, to, email_text)
    server.close()
    print('Email sent!')
except:
    print('Something went wrong...')

现在使用 sendmail 代替 send_message 编写代码

【问题讨论】:

  • 代替subject = subject 试试subject
  • 同无主题
  • 这能回答你的问题吗? stackoverflow.com/questions/29899542/…
  • 它的外观如何?
  • msg = '' for item in input("To: ").split(): msg['To'] = item like this?

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


【解决方案1】:

您需要使用sendmail() 而不是send_message()

import smtplib
user_name = 'my@gmail.com'
password = '*******'
to = ['my@gmail.com', 'other_email@gmail.com']
subject = 'Theme'
message = 'Test message'
email_message = 'Subject: {}\n\n{}'.format(subject, message) 
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
server.ehlo()
server.login(user_name, password)
server.send_message(user_name, to, email_message)
server.close()

参考:

  1. Python smtplib send_message() failing, returning AttributeError: 'str' object has no attribute 'get_all'
  2. Python: "subject" not shown when sending email using smtplib module

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-23
    • 2021-12-01
    • 2020-09-19
    • 2021-04-26
    • 1970-01-01
    • 2015-10-21
    • 2016-05-18
    • 2019-06-19
    相关资源
    最近更新 更多