您可能已经知道,某些邮件地址需要关闭gmail中安全性较低的应用的安全性。
关闭选项就像带有smtlib
和附件的超级按钮一样,但是不关闭就根本不起作用。
然后,我在ezgmail模块中发现了使用 Auth 2.0 的API方式,它可以非常轻松地发送电子邮件,但是attachmets的连接不是很好。它们在编码时存在一些问题,因为它们无法很好地显示文档。
我最终得到的代码是:
import ezgmail
import os, sys, glob
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
pathFile = '<path>'
folder = os.getcwd()
def compose():
# email_from = '<my email>'
subject = 'Hello,'
body = '''Here I put the text I want.'''
return [subject, body]
def send_email(email_to):
subject, body = compose()
ezgmail.EMAIL_ADDRESS = '<my email>' # email_from
os.chdir(pathFile)
list_pdfs = glob.glob('*.pdf')
file1 = max(list_pdfs, key=os.path.getctime) # select latest file
# this should do the *encode part*
attachment = open(file1, 'rb')
file = MIMEBase('application','octet-stream')
file.set_payload((attachment).read())
encoders.encode_base64(file)
os.chdir(folder)
ezgmail.send(email_to, subject, body, file.as_string())
print("Mail sent")
send_email(to@example.com)
问题在于:如何将文档(pdf,word,excel)正确地附加到ezgmail 上?
答案 0 :(得分:1)
附件必须是一个字符串(或字符串列表),代表文档的路径:
def send_email(email_to):
subject, body = compose()
ezgmail.EMAIL_ADDRESS = '<my email>' # email_from
os.chdir(pathFile)
list_pdfs = glob.glob('*.pdf')
file1 = max(list_pdfs, key=os.path.getctime) # select latest file
os.chdir(folder)
ezgmail.send(email_to, subject, body, os.sep.join([pathFile, file1]))
print("Mail sent")
编码是一个单独的问题。
作者说:
EZGmail并不全面,不能执行Gmail API允许的所有操作 你做到了,这意味着使简单的事情变得简单
它确实尝试进行MIME转换,但是没有特定于pdf文件的
需要在_createMessageWithAttachments方法中将以下代码插入EZgmail模块:
elif sub_type == 'pdf':
mimePart = MIMEBase('application','octet-stream')
mimePart.set_payload((fp).read())
encoders.encode_base64(mimePart)
您需要从电子邮件中导入编码器