Created
December 15, 2021 02:08
-
-
Save hqf00342/61b58e0ce8195578a8215e52d0784b50 to your computer and use it in GitHub Desktop.
awsのSESを使った添付ファイル送信プログラム
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python3 | |
# sendmailattach.py TO FROM SUBJECT BODY ATTACH_FILENAME | |
# TO = 送信先メールアドレス | |
# FROM = 送信元 | |
# SUBJECT = 題名 | |
# ATTACHMENT = 添付ファイル名 | |
# BODY_TEXT = 本文 | |
import sys | |
import os | |
import boto3 | |
import datetime | |
import re | |
import zipfile | |
from botocore.exceptions import ClientError | |
from email.mime.multipart import MIMEMultipart | |
from email.mime.text import MIMEText | |
from email.mime.application import MIMEApplication | |
def sendmail(RECIPIENT, SENDER, SUBJECT, BODY_TEXT,ATTACHMENT): | |
AWS_REGION = "ap-northeast-1" | |
client = boto3.client('ses',region_name=AWS_REGION) | |
msg = MIMEMultipart('mixed') | |
msg['Subject'] = SUBJECT | |
msg['From'] = SENDER | |
msg['To'] = RECIPIENT | |
msg_body = MIMEMultipart('alternative') | |
textpart = MIMEText(BODY_TEXT.encode("utf-8"), 'plain', "utf-8") | |
msg_body.attach(textpart) | |
att = MIMEApplication(open(ATTACHMENT, 'rb').read()) | |
att.add_header('Content-Disposition','attachment',filename=os.path.basename(ATTACHMENT)) | |
msg.attach(msg_body) | |
msg.attach(att) | |
try: | |
response = client.send_raw_email( | |
Source=SENDER, | |
Destinations=[ RECIPIENT ], | |
RawMessage={ 'Data':msg.as_string(), }, | |
) | |
except ClientError as e: | |
print(e.response['Error']['Message']) | |
else: | |
#print("Email sent! Message ID:"), | |
print(response['ResponseMetadata']['RequestId']) | |
# Main Function | |
if __name__ == "__main__": | |
if len(sys.argv) != 6: | |
print('引数が5つ必要です') | |
print() | |
print('sendmailattach.py TO FROM SUBJECT BODY ATTACHMENT') | |
print(' TO = 送信先メールアドレス') | |
print(' FROM = 送信元') | |
print(' SUBJECT = 題名') | |
print(' ATTACHMENT = 添付ファイル名') | |
print(' BODY_TEXT = 本文') | |
sys.exit(1) | |
args = sys.argv | |
sendmail(args[1], args[2], args[3], args[4], args[5]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment