【问题标题】:AWS Lambda (python 3.6) – creating text with hyperlinkAWS Lambda (python 3.6) – 创建带有超链接的文本
【发布时间】:2020-12-02 20:34:56
【问题描述】:

我将使用我的 Lambda 通过 SES 发送电子邮件通知,我想在电子邮件正文中创建一个超链接。

电子邮件正文示例:

请转到 doc www.example.com的链接

我试图创建类似这样的内容 -> {Guideline doc},但出现语法错误,不知道如何在文本中将其显示为某些文档的名称等。

我还需要在电子邮件正文中创建一个 HTML 表格,但我不知道这在 aws Lambda 中是否可行。

例子:

import json

import boto3

import csv

from datetime import datetime

 

def lambda_handler(event, context):

    for i in event['Records']:

        bucket_name = i['s3']['bucket']['name']

        object = i['s3']['object']['key']

        s3=boto3.client('s3')

        response=s3.get_object(Bucket=bucket_name,Key=object)

        csv_contents = response['Body'].read()

        csv_contents_decoded = csv_contents.decode('utf-8')

        reader=csv.reader(csv_contents_decoded.splitlines())

        print('type csv_contents_decoded:',type(csv_contents_decoded))

        print('type reader:',type(reader))

        print('csv_contents_decoded:',csv_contents_decoded)

        print('reader:',reader)

       

        

        currentMonth = datetime.now().month

        currentYear = datetime.now().year

        previousMonth = currentMonth-1

       

        owner_list = []

        sponsor_list = []

        for row in reader:

            owner_list.append(row[1]+'@example.com')

            sponsor_list.append(row[2]+'@example.com')

       

        

            

            

        

        

    client = boto3.client('ses')

    subject = 'Test'

    body = f'''

         <br>

         Test

         {previousMonth} is in {currentYear}.

         Text with hyperlink and html table.

 

        

        

         

    '''

        

    message = {'Subject': {'Data': subject}, 'Body': {'Html': {'Data': body}}}

    response = client.send_email(Source = 'test@domain.dev', Destination = {'ToAddresses': owner_list 'CcAddresses': sponsor_list},Message=message)   

        

    # TODO implement

    return {

        'statusCode': 200,

        'body': json.dumps('Hello from Lambda!')

    }


 

非常感谢您的建议。提前谢谢你。

【问题讨论】:

  • 您能否发布您用于发送消息的代码以及您遇到的错误?
  • 我想在正文中包含超链接和 html 表格作为一个电子邮件正文的一部分。因此,假设有 10 个超链接和一个 html 表格的文本,都在一个正文中。

标签: python amazon-web-services lambda hyperlink


【解决方案1】:

来自 AWS 开发人员指南中的 Send an email using the AWS SDK for Python (Boto) 示例(根据您的情况进行调整,重点关注 BODY_TEXTBODY_HTML):

import boto3
from botocore.exceptions import ClientError

# Replace sender@example.com with your "From" address.
# This address must be verified with Amazon SES.
SENDER = "Sender Name <sender@example.com>"

# Replace recipient@example.com with a "To" address. If your account 
# is still in the sandbox, this address must be verified.
RECIPIENT = "recipient@example.com"

# Specify a configuration set. If you do not want to use a configuration
# set, comment the following variable, and the 
# ConfigurationSetName=CONFIGURATION_SET argument below.
CONFIGURATION_SET = "ConfigSet"

# If necessary, replace us-west-2 with the AWS Region you're using for Amazon SES.
AWS_REGION = "us-west-2"

# The subject line for the email.
SUBJECT = "Amazon SES Test (SDK for Python)"

# The email body for recipients with non-HTML email clients.
BODY_TEXT = ("This is some regular text\r\n"
             "Please go to doc at the following link:"
             "http://www.example.com"
            )
            
# The HTML body of the email.
BODY_HTML = """<html>
<head></head>
<body>
  <p>This is some regular text</p>
  <a href='http://www.example.com'>Please go to doc</a>
</body>
</html>
            """            

# The character encoding for the email.
CHARSET = "UTF-8"

# Create a new SES resource and specify a region.
client = boto3.client('ses',region_name=AWS_REGION)

# Try to send the email.
try:
    #Provide the contents of the email.
    response = client.send_email(
        Destination={
            'ToAddresses': [
                RECIPIENT,
            ],
        },
        Message={
            'Body': {
                'Html': {
                    'Charset': CHARSET,
                    'Data': BODY_HTML,
                },
                'Text': {
                    'Charset': CHARSET,
                    'Data': BODY_TEXT,
                },
            },
            'Subject': {
                'Charset': CHARSET,
                'Data': SUBJECT,
            },
        },
        Source=SENDER,
        # If you are not using a configuration set, comment or delete the
        # following line
        ConfigurationSetName=CONFIGURATION_SET,
    )
# Display an error if something goes wrong. 
except ClientError as e:
    print(e.response['Error']['Message'])
else:
    print("Email sent! Message ID:"),
    print(response['MessageId'])

关于 HTML 表格,这里的限制是 HTML 可以做什么,最重要的是您所针对的浏览器/电子邮件客户端。表格的一个例子是:

<table>
    <thead>
        <tr>
            <th colspan="2">The table header</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>The table body</td>
            <td>with two columns</td>
        </tr>
    </tbody>
</table>

您可以找到关于 HTML 表格如何在 MDN herehere 上工作的很好参考。

【讨论】:

    【解决方案2】:

    我的解决方案:

    
    import json
    import boto3
    import csv
    from datetime import datetime
     
    def lambda_handler(event, context):
        for i in event['Records']:
            bucket_name = i['s3']['bucket']['name']
            object = i['s3']['object']['key']
            s3=boto3.client('s3')
            response=s3.get_object(Bucket=bucket_name,Key=object)
            csv_contents = response['Body'].read()
            csv_contents_decoded = csv_contents.decode('utf-8')
            reader=csv.reader(csv_contents_decoded.splitlines())
            print('type csv_contents_decoded:',type(csv_contents_decoded))
            print('type reader:',type(reader))
            print('csv_contents_decoded:',csv_contents_decoded)
            print('reader:',reader)
            
            
            currentYear = datetime.now().year
            curryear = int(str(currentYear)[-2:])
            months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
            current_month = datetime.now().month -1
            current_mnth = [months[(current_month)]]
            curr_mnth = ''.join(current_mnth)
            previous_mnth = [months[(current_month)-1]]
            prev_mnth = ''.join(previous_mnth)
            
            to_list = []
            cc_list = []
            for row in reader:
                to_list.append(row[1]+'@example.com')
                cc_list.append(row[2]+'@example.com')
            
                
                
            
            
        client = boto3.client('ses')
        subject = f'''[Update reminder] for {prev_mnth}'{curryear}'''
        table = """
        <html>
        <head>
        <style>
        table, th, td {
        border: 1px solid black;
        border-collapse: collapse;
        }
        th, td {
        padding: 15px;}
        
        </style>
        </head>
        <body>
     
        <table style="width:100%">
        <tr>
        <td>A</td>
        <td>B</td>
        <td>C</td>
        <td>D</td>
        </tr>
        <tr>
        <td>E</td>
        <td>text...</td>
        </tr>
        <tr>
        ...
        ...
        </tr>
        </table>
        </body>
        </html>
        """
        
        body = f'''
             <br>
             text...,<br>
            
             {table}
             <br>
             Thank you...
     
        '''
     
        message = {'Subject': {'Data': subject}, 'Body': {'Html': {'Data': body}}}
        response = client.send_email(Source = 'example@example.com', Destination = {'ToAddresses': to_list},Message=message)    
            
        # TODO implement
        return {
            'statusCode': 200,
            'body': json.dumps('Hello from Lambda!')
        }
    
    
    
    

    【讨论】:

      猜你喜欢
      • 2018-12-23
      • 2017-01-07
      • 1970-01-01
      • 2017-05-15
      • 1970-01-01
      • 2011-05-17
      • 2012-11-07
      • 2015-11-25
      • 1970-01-01
      相关资源
      最近更新 更多