The main thing is how to create the dynamic html body content for the email using API only?
Simple mail creation and sending is easy. What I have tried:
import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from flask import Flask, request, jsonify
import re
import csv
app = Flask(__name__)
app.run(debug=True,host='0.0.0.0', port=8085)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
#curl -F 'files=@email_body.html' -F metadata="{'send_from':'abc@mydomain.com', 'subject':'Hi from massmail api', 'send_to':'xyz2020@gmail.com'}" -X POST http://localhost:8085/mail
@app.route("/mail", methods=['POST'])
def send_mail():
server = "127.0.0.1"
smtp = smtplib.SMTP(server)
data = request.get_json(force=True)
files = request.files['files']
metadata = request.form.get("metadata")
send_from = None
mmeta = eval(metadata)
send_from = mmeta['send_from']
subject = mmeta["subject"]
text = 'Hi, how do you do. We are fine mailing'
msg = MIMEMultipart()
msg['From'] = send_from
msg['To'] = mmeta["send_to"]
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = mmeta["subject"]
msg.attach(MIMEText(text))
#for f in files or []:
# print(f,' ---file attachment')
# with open(f, "rb") as fil:
#with app.open_resource(f, "rb") as fil:
# part = MIMEApplication(
# fil.read(),
# Name=basename(f)
# )
# After the file is closed
# part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
# msg.attach(part)
smtp.sendmail(send_from, msg["To"], msg.as_string())
#print('mail sent:', row['email'])
smtp.close()
return jsonify({'Mail sent successfully' : subject}), 200
if __name__ == "__main__":
app.run(debug=True,host='0.0.0.0', port=8085)
I also need to create normal text body for the mail in the same way for the same email. The best option is to upload the text and html body content file. But how to work with the api and the corresponding curl for the same, please guide.