Gmail Python多附件

Gmail Python多附件,python,gmail,email-attachments,Python,Gmail,Email Attachments,我正在尝试创建一个小脚本,它将使用gmail发送多个附件。下面的代码发送电子邮件,但不发送附件。预期用途是cron一对数据库查询并通过电子邮件发送结果。始终会有2个文件,并且文件名每天都会不同,因为报告的日期在文件名中。否则我只会使用: part.add_header('Content-Disposition', 'attachment; filename="absolute Path for the file/s"') 非常感谢您的帮助 import os import smtpl

我正在尝试创建一个小脚本,它将使用gmail发送多个附件。下面的代码发送电子邮件,但不发送附件。预期用途是cron一对数据库查询并通过电子邮件发送结果。始终会有2个文件,并且文件名每天都会不同,因为报告的
日期在文件名中。否则我只会使用:

part.add_header('Content-Disposition', 
    'attachment; filename="absolute Path for the file/s"')
非常感谢您的帮助

import os
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.MIMEBase import MIMEBase
from email import Encoders


#Set up crap for the attachments
files = "/tmp/test/dbfiles"
filenames = [os.path.join(files, f) for f in os.listdir(files)]
#print filenames


#Set up users for email
gmail_user = "joe@email.com"
gmail_pwd = "somepasswd"
recipients = ['recipient1','recipient2']

#Create Module
def mail(to, subject, text, attach):
   msg = MIMEMultipart()
   msg['From'] = gmail_user
   msg['To'] = ", ".join(recipients)
   msg['Subject'] = subject

   msg.attach(MIMEText(text))

   mailServer = smtplib.SMTP("smtp.gmail.com", 587)
   mailServer.ehlo()
   mailServer.starttls()
   mailServer.ehlo()
   mailServer.login(gmail_user, gmail_pwd)
   mailServer.sendmail(gmail_user, to, msg.as_string())
   # Should be mailServer.quit(), but that crashes...
   mailServer.close()

#get all the attachments
   for file in filenames:
      part = MIMEBase('application', 'octet-stream')
      part.set_payload(open(file, 'rb').read())
      Encoders.encode_base64(part)
      part.add_header('Content-Disposition', 'attachment; filename="%s"'
                   % os.path.basename(file))
      msg.attach(part)
#send it
mail(recipients,
   "Todays report",
   "Test email",
   filenames)

应该再等一个小时再发帖。 进行了2项更改:

1.)将附件循环向上移动

2)调出 part.add_头('Content-Disposition','attachment;filename=“%s”' %os.path.basename(文件))

对于part.add_头('Content-Disposition','attachment;filename=“%s”%file)

像冠军一样工作。有多个收件人和多个附件的Gmail

import os 
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
from email.MIMEImage import MIMEImage
from email.MIMEBase import MIMEBase
from email import Encoders


#Set up crap for the attachments
files = "/tmp/test/dbfiles"
filenames = [os.path.join(files, f) for f in os.listdir(files)]
#print filenames


#Set up users for email
gmail_user = "joe@email.com"
gmail_pwd = "somepasswd"
recipients = ['recipient1','recipient2']

#Create Module
def mail(to, subject, text, attach):
   msg = MIMEMultipart()
   msg['From'] = gmail_user
   msg['To'] = ", ".join(recipients)
   msg['Subject'] = subject

   msg.attach(MIMEText(text))

   #get all the attachments
   for file in filenames:
      part = MIMEBase('application', 'octet-stream')
      part.set_payload(open(file, 'rb').read())
      Encoders.encode_base64(part)
      part.add_header('Content-Disposition', 'attachment; filename="%s"' % file)
      msg.attach(part)

   mailServer = smtplib.SMTP("smtp.gmail.com", 587)
   mailServer.ehlo()
   mailServer.starttls()
   mailServer.ehlo()
   mailServer.login(gmail_user, gmail_pwd)
   mailServer.sendmail(gmail_user, to, msg.as_string())
   # Should be mailServer.quit(), but that crashes...
   mailServer.close()

#send it
mail(recipients,
   "Todays report",
   "Test email",
   filenames)
谢谢@marc! 我无法对您的答案发表评论,因此这里有一些修复(错误命名的变量)和小的改进:

import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import MIMEImage
from email.mime.base import MIMEBase
from email import Encoders

def mail(to, subject, text, attach):
    # allow either one recipient as string, or multiple as list
    if not isinstance(to,list):
        to = [to]
    # allow either one attachment as string, or multiple as list
    if not isinstance(attach,list):
        attach = [attach]

    gmail_user='username@gmail.com'
    gmail_pwd = "password"
    msg = MIMEMultipart()
    msg['From'] = gmail_user
    msg['To'] = ", ".join(to)
    msg['Subject'] = subject

    msg.attach(MIMEText(text))

    #get all the attachments
    for file in attach:
        print file
        part = MIMEBase('application', 'octet-stream')
        part.set_payload(open(file, 'rb').read())
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
        msg.attach(part)

    mailServer = smtplib.SMTP("smtp.gmail.com", 587)
    mailServer.ehlo()
    mailServer.starttls()
    mailServer.ehlo()
    mailServer.login(gmail_user, gmail_pwd)
    mailServer.sendmail(gmail_user, to, msg.as_string())
    # Should be mailServer.quit(), but that crashes...
    mailServer.close()

if __name__ == '__main__':
    mail(['recipient1', 'recipient2'], 'subject', 'body text',
         ['attachment1', 'attachment2'])

我也有类似的问题。我可以发送多个附件,但在我的Mac mail应用程序上,并非所有附件都会显示,html也不会显示(在Gmail web上,一切正常)。如果有人有同样的问题,下面的代码在python3.8中为我工作。所有附件和html现在都显示在邮件应用程序上

更新很少:

import os, ssl, sys
import smtplib
# For guessing MIME type based on file name extension
import mimetypes
from email.message import EmailMessage
from email.policy import SMTP
from datetime import datetime
from uuid import uuid4

directory = '/path/to/files'
recipients = ['recipient@gmail.com']
sender = 'username@gmail.com'
password = 'password'
email_host, email_port = 'smtp.gmail.com', 465

msg = EmailMessage()
msg['Subject'] = f'This is a subject {datetime.utcnow()}'
msg['To'] = ', '.join(recipients)
msg['From'] = sender
msg.preamble = f'{str(uuid4())}\n'

msg.add_alternative('This is a PLAIN TEXT', subtype='plain')
msg.add_alternative('''\
    <html>
    <head></head>
    <body>
        <h4>Hello World! this is HTML </h4>
        <p style="margin: 0;">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
        tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat.</p>
    </body>
    </html>''', subtype='html')

for filename in ['sample.pdf', 'sample2.pdf']:
    path = os.path.join(directory, filename)
    if not os.path.isfile(path):
        continue
    # Guess the content type based on the file's extension.  Encoding
    # will be ignored, although we should check for simple things like
    # gzip'd or compressed files.
    ctype, encoding = mimetypes.guess_type(path)
    if ctype is None or encoding is not None:
        # No guess could be made, or the file is encoded (compressed), so
        # use a generic bag-of-bits type.
        ctype = 'application/octet-stream'
    maintype, subtype = ctype.split('/', 1)
    with open(path, 'rb') as fp:
        msg.add_attachment(fp.read(),
                            maintype=maintype,
                            subtype=subtype,
                            filename=filename)

context = ssl.create_default_context()
with smtplib.SMTP_SSL(email_host, email_port, context=context) as server:
    server.login(sender, password)
    server.send_message(msg)




导入操作系统、ssl、系统
导入smtplib
#用于根据文件扩展名猜测MIME类型
导入模拟类型
从email.message导入EmailMessage
从email.policy导入SMTP
从日期时间导入日期时间
从uuid导入uuid4
目录='/path/to/files'
收件人=['recipient@gmail.com']
发送者username@gmail.com'
密码='password'
电子邮件主机,电子邮件端口='smtp.gmail.com',465
msg=EmailMessage()
msg['Subject']=f'这是一个主题{datetime.utcnow()}'
msg['To']=','.加入(收件人)
msg['From']=发件人
msg.preamble=f'{str(uuid4())}\n'
msg.add_alternative('这是纯文本',subtype='PLAIN')
msg.添加替代品(“”)\
你好,世界!这是HTML
Lorem ipsum Door sit amet、Concetetur Adipising Elite、sed do eiusmod
暂时性的劳动和财产损失,
他在乌拉姆科实验室实习,并在普通实验室实习
康塞奎特

'',子类型='html') 对于['sample.pdf','sample2.pdf']中的文件名: path=os.path.join(目录,文件名) 如果不是os.path.isfile(路径): 持续 #根据文件扩展名猜测内容类型。编码 #将被忽略,尽管我们应该检查一些简单的事情,如 #gzip文件或压缩文件。 ctype,encoding=mimetypes.guess\u类型(路径) 如果ctype为None或encoding为None: #无法猜测,或者文件已编码(压缩),因此 #使用bits类型的通用包。 ctype='应用程序/八位字节流' maintype,subtype=ctype.split(“/”,1) 打开(路径“rb”)作为fp: msg.add_附件(fp.read(), maintype=maintype, 子类型=子类型, 文件名=文件名) context=ssl.create\u default\u context() 使用smtplib.SMTP\u SSL(电子邮件\u主机,电子邮件\u端口,上下文=上下文)作为服务器: 服务器登录名(发件人、密码) 服务器发送消息(msg)
请熟悉本网站的工作原理。这不是一个讨论论坛,而是一个严格的问答网站。如果您有问题,请将其作为新问题(以及参考相关问题)提出,不要像您当前所做的那样将其作为相关问题的答案发布。答案只能用于实际回答问题。