Skip to content

Instantly share code, notes, and snippets.

@matetsu
Created December 10, 2015 14:32
Show Gist options
  • Save matetsu/d6b3d5e2339713e58276 to your computer and use it in GitHub Desktop.
Save matetsu/d6b3d5e2339713e58276 to your computer and use it in GitHub Desktop.
SES -> S3 -> Lambda -> Slack
[slack]
hook_url = https://hooks.slack.com/services/xxxxxxx/yyyyyyyy/zzzzzzzzzzzzzzzzzzzzzzzzzzzzzz
username = alert_bot
channel = #alert
icon_emoji = :guardsman:
# coding: utf-8
import boto3
import json
import ConfigParser
from email.parser import FeedParser
from email.header import decode_header
import slackweb
def lambda_handler(event, context):
try:
record = event["Records"][0]
bucket_region = record["awsRegion"]
bucket_name = record["s3"]["bucket"]["name"]
mail_object_key = record["s3"]["object"]["key"]
s3 = boto3.client('s3', region_name=bucket_region)
mail_object = s3.get_object(Bucket = bucket_name, Key = mail_object_key)
mail_body = ''
try:
mail_body = mail_object["Body"].read().decode('utf-8')
except:
try:
mail_body = mail_object["Body"].read().decode('iso-2022-jp')
except:
mail_body = mail_object["Body"].read()
parser = FeedParser()
parser.feed(mail_body)
parsed_mail = parser.close()
(d_sub, sub_charset) = decode_header(parsed_mail['Subject'])[0]
subject = d_sub.decode(sub_charset)
payload = parsed_mail.get_payload(decode=parsed_mail['Content-Transfer-Encoding'])
body_charset = parsed_mail.get_content_charset()
body = payload.decode(body_charset)
except:
subject = u"Error!"
body = u"メールを受信しましたが、エラーが発生しました。"
inifile = ConfigParser.SafeConfigParser()
inifile.read("./config.ini")
attachments = []
attachment = {
"fallback": u"メールです。",
"pretext": u"メールです。 (key: %s)" % mail_object_key,
"color": "#aaaaaa",
"fields": [
{
"title": subject,
"value": body,
"short": False
}
]
}
attachments.append(attachment)
slack = slackweb.Slack(url=inifile.get('slack', 'hook_url'))
slack.notify(attachments=attachments,
channel=inifile.get('slack', 'channel'),
username=inifile.get('slack', 'username'),
icon_emoji=inifile.get('slack', 'icon_emoji'))
return "CONTINUE"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment