使用gmail smtp使用python发送邮件

使用gmail smtp使用python发送邮件,python,email,smtp,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 im

我正在使用以下代码

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” 正如上面所写的,我已经更改了允许不太安全的应用程序:ON

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

的全部目的(我是开发人员)是使发送电子邮件变得非常容易,特别是对于HTML或附件的需要

请尝试以下代码:

import yagmail
yag = yagmail.SMTP(username, password)
yag.send(emailto, subject = "I now can send an attachment", contents = fileToSend)
注意这里的神奇之处:
内容
等于文件路径,将使用正确的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

是您正在使用的完整地址的用户名。如:name@gmail.comyes! 执行时正确插入用户名和密码!刚刚结束的问题,它是否自动检测到mimetype?@0xc0de是的,它会@JamesMethew
pip3安装yagmail
,或者可以尝试
pip3.2安装yagmail
?@JamesMethew可能尝试运行
哪个python3
哪个pip3
。pip3和python3都可以