【问题标题】:Send Mail with python using gmail smtp使用 gmail smtp 使用 python 发送邮件
【发布时间】:2015-06-24 14:10:58
【问题描述】:

我正在使用以下代码

import smtplib
import mimetypes
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.text import MIMEText

emailfrom = "sender@example.com"
emailto = "destination@example.com"
fileToSend = "hi.csv"
username = "user"
password = "password"

msg = MIMEMultipart()
msg["From"] = emailfrom
msg["To"] = emailto
msg["Subject"] = "help I cannot send an attachment to save my life"
msg.preamble = "help I cannot send an attachment to save my life"

ctype, encoding = mimetypes.guess_type(fileToSend)
if ctype is None or encoding is not None:
    ctype = "application/octet-stream"

maintype, subtype = ctype.split("/", 1)

if maintype == "text":
    fp = open(fileToSend)
    # Note: we should handle calculating the charset
    attachment = MIMEText(fp.read(), _subtype=subtype)
    fp.close()
elif maintype == "image":
    fp = open(fileToSend, "rb")
    attachment = MIMEImage(fp.read(), _subtype=subtype)
    fp.close()
elif maintype == "audio":
    fp = open(fileToSend, "rb")
    attachment = MIMEAudio(fp.read(), _subtype=subtype)
    fp.close()
else:
    fp = open(fileToSend, "rb")
    attachment = MIMEBase(maintype, subtype)
    attachment.set_payload(fp.read())
    fp.close()
    encoders.encode_base64(attachment)
attachment.add_header("Content-Disposition", "attachment", filename=fileToSend)
msg.attach(attachment)

server = smtplib.SMTP("smtp.gmail.com:587")
server.starttls()
server.login(username,password)
server.sendmail(emailfrom, emailto, msg.as_string())
server.quit()

我收到错误 “不接受用户名和密码。在\n5.7.8 https://support.google.com/mail/answer/14257 了解更多信息” 按照那里写的,我已经改变了允许不太安全的应用程序:开

但得到同样的错误! 有什么帮助吗??

【问题讨论】:

  • 是您使用的用户名的完整地址。例如:name@gmail.com
  • 是的!执行时正确插入用户名密码!

标签: python email smtp


【解决方案1】:

yagmail(我是开发人员)的全部目的是让发送电子邮件变得非常容易,尤其是有 HTML 或附件需求时。

试试下面的代码:

import yagmail
yag = yagmail.SMTP(username, password)
yag.send(emailto, subject = "I now can send an attachment", contents = fileToSend)

注意这里的神奇之处:contents 等于文件路径会自动附加,使用正确的 mimetype。

如果你想用它发送文本,你可以这样做:

contents = ['Please see the attachment below:', fileToSend, 'cool huh?']

如果您想讨论附件而不是发送附件,只需确保列表中没有参数只是文件路径。

contents = 'This filename will not be attached ' + fileToSend

你可以通过pip安装得到yagmail:

pip install yagmail # Python 2
pip3 install yagmail # Python 3

【讨论】:

  • 问个问题,它会自动检测 mimetype 吗?
  • @0xc0de 是的!
  • @JamesMethew pip3 install yagmail,或者pip3.2 install yagmail可以试试?
  • @JamesMethew 也许尝试运行which python3 和which pip3。
  • pip3 和 python3 都
猜你喜欢
  • 1970-01-01
  • 2017-11-14
  • 2015-09-28
  • 1970-01-01
  • 2016-10-25
  • 2015-05-28
  • 2014-09-13
  • 1970-01-01
相关资源
最近更新 更多