AWS Lambda (python 3.6) – 创建带超链接的文本
AWS Lambda (python 3.6) – creating text with hyperlink
我将使用我的 Lambda 通过 SES 发送电子邮件通知,我想在电子邮件正文中创建一个 hyperlink。
示例电子邮件正文:
请转到文档 <- 单击“Guide doc”一词后,我会看到一个 link,例如 www.example.com
我试图创建类似这样的东西 -> {Guideline doc} 但我遇到语法错误不知道如何在文本中将其显示为某个文档的名称等。
我还需要在电子邮件正文中创建一个 HTML Table,但我不知道这在 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!')
}
非常感谢您的建议。提前谢谢你。
来自 AWS 开发人员指南的 Send an email using the AWS SDK for Python (Boto) 示例(根据您的情况进行调整,重点放在 BODY_TEXT
和 BODY_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 table,这里的限制是 HTML 可以做什么,最重要的是您的目标 browsers/email 客户。 table 的一个例子是:
<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>
我的解决方案:
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!')
}
我将使用我的 Lambda 通过 SES 发送电子邮件通知,我想在电子邮件正文中创建一个 hyperlink。
示例电子邮件正文:
请转到文档 <- 单击“Guide doc”一词后,我会看到一个 link,例如 www.example.com
我试图创建类似这样的东西 -> {Guideline doc} 但我遇到语法错误不知道如何在文本中将其显示为某个文档的名称等。
我还需要在电子邮件正文中创建一个 HTML Table,但我不知道这在 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!')
}
非常感谢您的建议。提前谢谢你。
来自 AWS 开发人员指南的 Send an email using the AWS SDK for Python (Boto) 示例(根据您的情况进行调整,重点放在 BODY_TEXT
和 BODY_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 table,这里的限制是 HTML 可以做什么,最重要的是您的目标 browsers/email 客户。 table 的一个例子是:
<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>
我的解决方案:
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!')
}