'How to create flask api call to create dynamic html email content body from a file and send mail using smtplib?
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':'[email protected]', 'subject':'Hi from massmail api', 'send_to':'[email protected]'}" -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.
Solution 1:[1]
This seems to be the main question you are asking based on the comments below your quesion: How do I upload the html and txt files to your flask app via curl? And my suggestion is to review this answer which is a post via curl using a name field for text and a filedata field for file storage:
From mata's answer:
curl -i -X PUT -F name=Test -F [email protected] "http://localhost:5000/"
python:
file = request.files['filedata'] # gives you a FileStorage
test = request.form['name'] # gives you the string 'Test'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Allen M |
