Skip to content

Commit 95763f0

Browse files
Create EC2_Code.py
Code: The code below will execute the SMTP protocol as soon as a file reaches the folder where this code is located. Instructions: Place this code in the created folder. The folder name should be the same as the one mentioned in the lambda code.
1 parent 7d570f3 commit 95763f0

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

EC2_Code.py

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
from flask import Flask, request, jsonify
2+
import smtplib
3+
import csv
4+
import os
5+
import boto3
6+
from werkzeug.utils import secure_filename
7+
8+
app = Flask(__name__)
9+
10+
# Define the upload folder for the CSV file
11+
UPLOAD_FOLDER = '/tmp'
12+
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
13+
14+
# Define the allowed file extensions
15+
ALLOWED_EXTENSIONS = {'csv'}
16+
17+
def allowed_file(filename):
18+
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
19+
20+
@app.route('/send-emails', methods=['POST'])
21+
def send_emails():
22+
data = request.get_json()
23+
24+
# Extract data from the request
25+
bucket = data['bucket']
26+
key = data['key']
27+
filename = data['filename']
28+
sender_email = data['sender_email']
29+
sender_password = data['sender_password']
30+
subject = data['subject']
31+
body = data['body']
32+
33+
# Download the file from S3
34+
s3 = boto3.client('s3')
35+
s3.download_file(bucket, key, os.path.join(app.config['UPLOAD_FOLDER'], filename))
36+
37+
if allowed_file(filename):
38+
# Read the CSV file and send emails
39+
with open(os.path.join(app.config['UPLOAD_FOLDER'], filename), 'r') as f:
40+
reader = csv.reader(f)
41+
for row in reader:
42+
recipient_email = row[1]
43+
if '@' in recipient_email:
44+
try:
45+
# Set up the SMTP server
46+
if 'outlook.com' in sender_email:
47+
host = 'smtp-mail.outlook.com
48+
port = 587
49+
elif 'gmail.com' in sender_email:
50+
host = 'smtp.gmail.com'
51+
port = 587
52+
53+
smtp = smtplib.SMTP(host, port)
54+
smtp.ehlo()
55+
smtp.starttls()
56+
smtp.login(sender_email, sender_password)
57+
58+
# Send the email
59+
msg = f'Subject: {subject}\n\n{body}'
60+
smtp.sendmail(sender_email, recipient_email, msg)
61+
smtp.quit()
62+
print(f'Email sent to {recipient_email}')
63+
except Exception as e:
64+
print(f'Error sending email to {recipient_email}: {str(e)}')
65+
66+
return jsonify({'message': 'Emails sent successfully'}), 200
67+
else:
68+
return jsonify({'error': 'Invalid file type'}), 400
69+
70+
if __name__ == '__main__':
71+
app.run(debug=True, host='0.0.0.0', port=5000)

0 commit comments

Comments
 (0)