繁体   English   中英

使用 gmail smtp 使用 python 发送邮件

[英]Send Mail with python using gmail smtp

我正在使用以下代码

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 上了解更多信息”,按照那里写的,我已经更改了允许不太安全的应用程序:开

但得到同样的错误! 任何帮助?

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

试试下面的代码:

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

请注意这里的法宝: contents等于文件路径会自动连接,使用正确的MIME类型。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM