使用gmail smtp使用python发送邮件

时间:2015-06-24 05:55:47

标签: python email 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了解更多信息。” 根据那里写的,我已经改变了允许不太安全的应用程序:ON

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

1 个答案:

答案 0 :(得分:2)

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