我正在使用下面的代码
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()
我遇到了错误 “不接受用户名和密码。在 5.7.8 https://support.google.com/mail/answer/14257 了解更多信息” 按照那里写的,我已经改变了允许安全性较低的应用程序:ON
但得到同样的错误! 有帮助吗??
请您参考如下方法:
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
yagmail可以通过pip安装获取:
pip install yagmail # Python 2
pip3 install yagmail # Python 3
