首页 > 解决方案 > python中的SES电子邮件附件

问题描述

使用 Python 3.7,在 lambda 包中部署一个文本文件:'sample.txt',并将 python 程序的日志写入该文本文件。现在,我正在尝试附加此文本文件并使用 mime 库通过 aws-SES 发送电子邮件。注意:在 Lambda 函数中执行整个程序。这是我在 lambda 函数中的代码:

import json, boto3
import logging as logger
import pathlib
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import os

def lambda_handler(event, context):

    #path = pathlib.Path().absolute()
    filename = ‘/tmp/sample.txt'
    logger.basicConfig(filename=filename, format='%(message)s',
                    level=logger.DEBUG, filemode='wt')
    #write these logs to text file
    logger.info(filename)
    logger.warning('233')
    logger.error('....')

    from = "abc@sample.com"
    to = "xyz@sample.com"
    region = "sample region"
    subject = "sample email"

    body = """<html>
    <head></head>
    <body>
      <h1>Test</h1>
      <p>This email was sent for testing</p>
    </body>
    </html>
               """            
    ses = boto3.client('ses',region_name=region)

    msg = MIMEMultipart()
    msg["Subject"] = subject
    msg["From"] = from
    msg["To"] = to

    body_txt = MIMEText(body, "html")
    msg.attach(body_txt)
    fo= open(filename, 'rb')
    file_content =fo.read()
    attachment = MIMEApplication(file_content)
    fo.close()
    attachment.add_header("Content-Disposition", "attachment", filename=filename)
    msg.attach(attachment)

    response = ses.send_raw_email(Source = from, Destinations = [to], RawMessage = {"Data": msg.as_string()})

"errorMessage": "[Errno 2] 没有这样的文件或目录:'/var/task/sample.txt'",

  1. 这是因为 /var/task 在执行完函数后会被删除吗?
  2. 在 S3 中保存文本文件,是唯一的选择吗?

标签: python-3.xamazon-web-servicesamazon-s3aws-lambda

解决方案


推荐阅读