Azure functions to send email with logo using sendgrid - python

I am sending email from Azure functions using python and sendgrid. I am able to form the other part of the email but when I am trying to insert logo in signature of the email is not displaying that. Rest HTML is rendering fine.(till href)
Following is my code :
import sendgrid
from sendgrid import SendGridAPIClient
from sendgrid.helpers.mail import Mail
message = Mail(
from_email=email_from,
to_emails=email_to,
subject=email_subject,
html_content= '<br>Hi '+name+ ','+
'<br>body of the email. Working fine.' +
'<br><a href='+no+'>No'</a>\n' +
'<br><br>LOGO--><img src="doc.png" alt="W3Schools.com"/>'+
'</html>'
)
response = sg.send(message)
print(response.status_code)
I tried pointing out URL in src too and it did not help.

There are 3 options to achieve this:
CID Embedded Images (Inline Images)
Inline Embedding (Base64 Encoding)
Linked Images
Check out below links for implementation details:
https://sendgrid.com/blog/embedding-images-emails-facts/
https://github.com/sendgrid/sendgrid-python/issues/736

Related

Sending Dynamic file path from Azure Databricks Code to Azure Logic apps for email attachments

Hi I am new to logic apps. I have a python code for sending mail with attachments using Azure Logic Apps. When I provide a static file path in Get Blob Content the mail is working fine with the attachment. But when I am trying to the send the file path dynamically from azure databricks it is not receiving at the get blob content in logic app. I have also tried few examples using initialise variables but it is not working.
import requests
def send_email(_to, _subject, _body, file):
email_body = "{0} <br><br><br> <h6> Hi Hello World </h6>".format(_body)
task = { "body_data_1": email_body , "subject_name_1": _subject , "email_to_list_1": _to, "attach" : file }
logic_app_post_url = 'https://prod-27.centralindia.logic.azure.com:443/workflows/*****'
resp = requests.post(logic_app_post_url, json=task)
print(resp.status_code)
if resp.status_code == 202:
print('Email Sent!')
email_to = "abc#outlook.com"
email_subject = "Testing Logic App Send Mail with Dynamic File"
email_body = "Hi This is a test mail Dynamic"
file_path = "/super-store/output/orders/_SUCCESS"
send_email(email_to, email_subject, email_body, file_path)
Logic App Design
Logic App Run Error Details
HTTP Input
HTTP Output
Get Blob Content Input
Get Blob Content Output
We have observed Get Blob Content (V2) is being used to send the attachments dynamically from azure Data bricks. Instead, we suggest using Get Blob Content using Path(V2) connector.
Wherein Get Blob Content (V2) connector will retrieve blob contents using id and Get Blob Content using Path (V2) connector retrieves blob contents using path.
Example with snippets:
Result:

Using Python and gmail API, how can I send messages with multiple attachements?

Looking to create and send messages with multiple files attached. Per the online gmail api documentation, there is a function for building messages with an attachment but no documentation for howto use it to create a message with multiple attachments.
Can I use the gmail API to send messages with multiple attachments programmatically? How might one do this?
With this function, you can send to one or multiple recipient emails, and also you can attach zero, one or more files. Coding improvement recommendations are welcome, however the way it is now, it works.
Python v3.7
smtplib from https://github.com/python/cpython/blob/3.7/Lib/smtplib.py (download the code and create the smtplib.py on your project folder)
def send_email(se_from, se_pwd, se_to, se_subject, se_plain_text='', se_html_text='', se_attachments=[]):
""" Send an email with the specifications in parameters
The following youtube channel helped me a lot to build this function:
https://www.youtube.com/watch?v=JRCJ6RtE3xU
How to Send Emails Using Python - Plain Text, Adding Attachments, HTML Emails, and More
Corey Schafer youtube channel
Input:
se_from : email address that will send the email
se_pwd : password for authentication (uses SMTP.SSL for authentication)
se_to : destination email. For various emails, use ['email1#example.com', 'email2#example.com']
se_subject : email subject line
se_plain_text : body text in plain format, in case html is not supported
se_html_text : body text in html format
se_attachments : list of attachments. For various attachments, use ['path1\file1.ext1', 'path2\file2.ext2', 'path3\file3.ext3']. Follow your OS guidelines for directory paths. Empty list ([]) if no attachments
Returns
-------
se_error_code : returns True if email was successful (still need to incorporate exception handling routines)
"""
import smtplib
from email.message import EmailMessage
# Join email parts following smtp structure
msg = EmailMessage()
msg['From'] = se_from
msg['To'] = se_to
msg['Subject'] = se_subject
msg.set_content(se_plain_text)
# Adds the html text only if there is one
if se_html_text != '':
msg.add_alternative("""{}""".format(se_html_text), subtype='html')
# Checks if there are files to be sent in the email
if len(se_attachments) > 0:
# Goes through every file in files list
for file in se_attachments:
with open(file, 'rb') as f:
file_data = f.read()
file_name = f.name
# Attaches the file to the message. Leaves google to detect the application to open it
msg.add_attachment(file_data, maintype='application', subtype='octet-stream', filename=file_name)
# Sends the email that has been built
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(se_from, se_pwd)
smtp.send_message(msg)
return True
Don't forget to activate less secure apps on your google account (https://myaccount.google.com/lesssecureapps) for this code to work.
Hope this helps

Send html email using flask in Python

I want to send HTML webpage as a mail body using Python and Flask. I tried using MIME module, but somehow I am not being able to send mail. If anyone has any expertise on this, can you please help me.
It would be great if you could provide some code as well.
flask-mail is a good tool that I use to render the template to render HTML as the body of my mail.
from flask_mail import Message
from flask import render_template
MAIL_USERNAME = os.environ.get('MAIL_USERNAME')
MAIL_PASSWORD = os.environ.get('MAIL_PASSWORD')
def send_mail_flask(to,subject,template,**kwargs):
msg = Message(subject=subject,sender='email#ofTheSender.com', recipients=to)
msg.body = render_template('template.txt', **kwargs)
msg.html = render_template('template.html', **kwargs)
mail.send(msg)
The template is the HTML file you wish to include in your mail and you can also add a text version using msg.body!
You may need to add more environment variables according to the SMTP service you use.
I recently made a pretty awesome email library and I decided to make a Flask extension for it as well: Flask-Redmail
Install
pip install flask-redmail
Configuration
from flask import Flask
from flask_redmail import RedMail
app = Flask(__name__)
email = RedMail(app)
# Setting configs
app.config["EMAIL_HOST"] = "localhost"
app.config["EMAIL_PORT"] = 0
app.config["EMAIL_USERNAME"] = "me#example.com"
app.config["EMAIL_PASSWORD"] = "<PASSWORD>"
app.config["EMAIL_SENDER"] = "no-reply#example.com"
Simple Example
You may send emails simply:
#app.route("/send-email")
def send_email():
email.send(
subject="Example email",
receivers=["you#example.com"],
html="""
<h1>Hi,</h1>
<p>this is an example.</p>
"""
)
Template Example
It can also use your default Jinja env. Create a file emails/verify.html to your Flask template folder that looks like this:
<h1>Hi, you visited {{ request.endpoint }}.</h1>
Then use this template:
#app.route("/send-email-template")
def send_email():
email.send(
subject="Template example",
receivers=["you#example.com"],
html_template="emails/verify.html"
)
Flask Redmail is quite a simple wrapper for Red Mail and Red Mail is pretty extensive. It can:
Send attachments from various types
Embed images and plots to the HTML
Embed prettified tables to the HTML
Supports Jinja out-of-the-box
Gmail and Outlook are preconfigured
I hope you find it useful.
Links:
Documentation
Source Code
Releases
Red Mail:
Documentation
Source Code
Releases
Try using FlaskMail https://pythonhosted.org/flask-mail/
msg = Message(
recipients=[''],
sender='xx#zz.yy',
reply_to='aa#bb.cc',
subject=mail.subject
)
msg.html = mail.body
mail.send(msg)
here, mail is an imported file from "mails" directory,
and body is an HTML markup.
On a separate python file (emails.py) I created an email class that contains all the emails (as class methods) to be sent to the user based on his actions as below:
class Email:
def accountCreation():
body = "<html> <body> <p> {} </p> <br> <br> <p> Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p> </body> </html>"
return body
then on another file (app.py) where I made use of flask_mail library I have:
from flask_mail import Mail, Message
import emails
mailer = emails.Email()
try:
email = "johndoe#mail.com"
body = mailer.accountCreation()
msg = Message('Hello',recipients=[email])
msg.html = body
mail.send(msg)
except Exception as e:
print(e)
Firstly, ensure there's a folder in your apps directory called templates. This is where all your html templates should be.
**server.py**
from flask-mail import Mail, Message
from flask import Flask
import os
app = Flask(__name__)
send_mail = Mail(app)
context={
"fullname": fullname,
"otp_code": otp_code,
"year": datetime.now().year,
"subject":"Registration Mail",
}
email_message = Message(
subject=mail_subject,
sender=os.getenv("ADMIN_EMAIL"),
recipients=[receipients_email],
html=render_template(template_name_or_list="otp.html", **context)
)
send_mail.send(email_message)
where "otp.html" is an existing html template in your templates folder

how to use designed template in django using sendgrid API?

I have integrate the send-grid with my Django application and mails also sent successfully. But now I want to send email with designed template from my django application. I have read the docs also, but not get any idea how to use it programatically. This is my first time to use send-grid. Please can anyone help me to find out the way how can I send send-grid template from django application.
You can use SendGrid's Template Engine to store a template inside SendGrid. You then reference that template ID when sending an email via the SendGrid API, you can see an example of that code in the sendgrid-python library.
Here it is in a full example, it uses a SendGrid API key (you can find out how to get that set up by reading this guide):
import sendgrid
sg = sendgrid.SendGridClient('sendgrid_apikey')
message = sendgrid.Mail()
message.add_to('John Doe <john#email.com>')
message.set_subject('Example')
message.set_html('Body')
message.set_text('Body')
message.set_from('Doe John <doe#email.com>')
# This next section is all to do with Template Engine
# You pass substitutions to your template like this
message.add_substitution('-thing_to_sub-', 'Hello! I am in a template!')
# Turn on the template option
message.add_filter('templates', 'enable', '1')
# Tell SendGrid which template to use
message.add_filter('templates', 'template_id', 'TEMPLATE-ALPHA-NUMERIC-ID')
# Get back a response and status
status, msg = sg.send(message)
You need Sendgrid-Python interface first:
pip install sendgrid
after that try this:
import os
from sendgrid.helpers.mail import Mail
from sendgrid import SendGridAPIClient
FROM_EMAIL = 'Your_Name#SendGridTest.com'
# update to your dynamic template id from the UI
TEMPLATE_ID = 'd-d027f2806c894df38c59a9dec5460594'
# list of emails and preheader names, update with yours
TO_EMAILS = [('your_email#domain.com', 'Sourabh MbeforL'),]
def SendDynamic():
message = Mail(
from_email=FROM_EMAIL,
to_emails=TO_EMAILS)
# pass custom values for our HTML placeholders
message.dynamic_template_data = {
'subject': 'SendGrid Development',
'place': 'New York City',
'event': 'Twilio Signal'
}
message.template_id = TEMPLATE_ID
try:
sg = SendGridAPIClient(os.environ.get('YOUR_SENDGRID_API_KEY')) ## (^_^) This face is just to grab your attention for api key needed
response = sg.send(message)
code, body, headers = response.status_code, response.body, response.headers
print(f"Response code: {code}")
print(f"Response headers: {headers}")
print(f"Response body: {body}")
print("Dynamic Messages Sent!")
except Exception as e:
print("Error: {0}".format(e))
return str(response.status_code)

Can't properly send HTML email with attached file via smtplib in python

I try to send email which contains text, html version of body and attached file.
I use standart python example with additional code:
img = MIMEImage(some_image_file)
img.add_header('Content-Disposition','attachment; filename="file.jpg"')
msg.attach(text_body)
msg.attach(html_body)
msg.attach(img)
Gmail show my email well, however yandex.com' email client shows only attached picture without html or text body of the letter.
If I change order like that:
msg.attach(img)
msg.attach(html_body)
Yandex shows only html body of my letter, and do not show attachment!
Is there any additional headers I need to add in order to show my email correctly (html/txt body AND attached file) in any email clients?
After some research of email headers sent from normal email client, I found solution:
body = MIMEMultipart('alternative')
msg = MIMEMultipart('mixed')
....
body.attach(text_body)
body.attach(html_body)
msg.attach(body)
msg.attach(img)

Categories