I want to send email using Django. In the mail body , I want to send Bootstrap "Card" which contain "Image" and HTML content.
Sending mail is successful. But, It is not showing the image in the received mail. Also, It is not in the Bootstrap "Card" format.
Please some one help me.
views.py
emailSubject = "Mail from XYZ.COM"
emailOfSender = EMAIL_HOST_USER
emailOfRecipient = viewed_bog.profile.user.email
html_content = render_to_string('receipt_email.html', {'item': viewed_bog, }, request=request)
try:
emailMessage = EmailMultiAlternatives(subject=emailSubject, body=html_content,
from_email=emailOfSender,
to=[emailOfRecipient, ], reply_to=[emailOfSender, ])
emailMessage.attach_alternative(html_content, "text/html")
emailMessage.send(fail_silently=False)
except SMTPException as e:
print('There was an error sending an email: ', e)
receipt_email.html
This is the HTML template containing Bootstrap 4 "Card" using Django-templating language. With in the Card I am having Image.
Now, I am able to send mail successfully. But Image is not showing in the received mail. and also, mail body is not in the "Card" format.
I will assume that you are loading the css from a bootstrap.css file and as most mail providers block loading css and js files for security reasons you should use inline styling in the template that you want to send.
Eventually this an online tool that i use when i want to compile regular css to inline css.
css inline tool
Related
I'm trying to design a PowerShell script that utilizes AWS SES to send a RawEmail with a .csv attachment, but information is scant on how to actually attach the attachment:
PS C:\Users\jsmith_prod\Desktop\SSMSScript> ls
Directory: C:\Users\jsmith_prod\Desktop\SSMS Script
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2/16/2023 2:00 PM 1096846 Inventory.csv
PS C:\Users\jsmith_prod\Desktop\SSMSScript> Send-SES2Email -FromEmailAddress jsmith#schwarma.com -Destination_ToAddress jsmith#schwarma.com -Raw_Data .\Inventory.csv
0100018661480af8-6a5939bd-5f9a-4f2f-9aa8-084cd872b9a8-000000
PS C:\Users\jsmith_prod\Desktop\SSMSScript>
When I try the above simple command, I only end up with an empty email, rather than an email with the attached .csv. According to AWS's documentation, attachments should be included under Raw_Data in order to highlight that this is a raw email. However, without any helpful error message, I can't figure out what's going wrong.
According to the Send-SES2Email documentation, the -Raw_Data argument is the raw email message itself, not an attachment. As you mentioned, attachments should be included under Raw_Data. The client must ensure that the message format complies with Internet email standards regarding email header fields, MIME types, and MIME encoding. The documentation defines criteria for raw messages and refers to RFC 5321 in that regard.
Please note, that the message body must contain a properly formatted, raw email message, with appropriate header fields and message body encoding. Although it's possible to construct the raw message manually within an application, it's much easier to do so using existing mail libraries. Check out this documentation for examples of how properly construct raw email message with an attachment. With Python it can look something like this (take note of how an attachment is handled):
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
# Replace sender#example.com with your "From" address.
# This address must be verified with Amazon SES.
SENDER = "Sender Name <sender#example.com>"
# Replace recipient#example.com with a "To" address. If your account
# is still in the sandbox, this address must be verified.
RECIPIENT = "recipient#example.com"
# Specify a configuration set. If you do not want to use a configuration
# set, comment the following variable, and the
# ConfigurationSetName=CONFIGURATION_SET argument below.
CONFIGURATION_SET = "ConfigSet"
# If necessary, replace us-west-2 with the AWS Region you're using for Amazon SES.
AWS_REGION = "us-west-2"
# The subject line for the email.
SUBJECT = "Customer service contact info"
# The full path to the file that will be attached to the email.
ATTACHMENT = "path/to/customers-to-contact.xlsx"
# The email body for recipients with non-HTML email clients.
BODY_TEXT = "Hello,\r\nPlease see the attached file for a list of customers to contact."
# The HTML body of the email.
BODY_HTML = """\
<html>
<head></head>
<body>
<h1>Hello!</h1>
<p>Please see the attached file for a list of customers to contact.</p>
</body>
</html>
"""
# The character encoding for the email.
CHARSET = "utf-8"
# Create a multipart/mixed parent container.
msg = MIMEMultipart('mixed')
# Add subject, from and to lines.
msg['Subject'] = SUBJECT
msg['From'] = SENDER
msg['To'] = RECIPIENT
# Create a multipart/alternative child container.
msg_body = MIMEMultipart('alternative')
# Encode the text and HTML content and set the character encoding. This step is
# necessary if you're sending a message with characters outside the ASCII range.
textpart = MIMEText(BODY_TEXT.encode(CHARSET), 'plain', CHARSET)
htmlpart = MIMEText(BODY_HTML.encode(CHARSET), 'html', CHARSET)
# Add the text and HTML parts to the child container.
msg_body.attach(textpart)
msg_body.attach(htmlpart)
# Define the attachment part and encode it using MIMEApplication.
att = MIMEApplication(open(ATTACHMENT, 'rb').read())
# Add a header to tell the email client to treat this part as an attachment,
# and to give the attachment a name.
att.add_header('Content-Disposition','attachment',filename=os.path.basename(ATTACHMENT))
# Attach the multipart/alternative child container to the multipart/mixed
# parent container.
msg.attach(msg_body)
# Add the attachment to the parent container.
msg.attach(att)
# Print message
print(msg.as_string())
I am able to get inbox emails and also able to get emails from specific folder but i am unable to get "starred" emails.
I tried below code. and i am expecting emails with "starred flag" in response.
from imap_tools import MailBox, A
# Create your views here.
def temp(request):
#Get date, subject and body len of all emails from INBOX folder
with MailBox('smtp.gmail.com').login('admin#gmail.com', 'password', 'INBOX') as mailbox:
temp="empty"
for msg in mailbox.fetch():
temp = (msg.date, msg.subject, msg.html)
return HttpResponse(temp)
https://github.com/ikvk/imap_tools/blob/master/examples/search.py
mailbox.fetch(AND(flagged=True))
(A long time ago in a galaxy far far away) star looked like a flag.
my django app is sending emails (via SendGrid API) using django.core.mail's send_mail
send_mail(
subject='foo',
message=message,
from_email=settings.DEFAULT_FROM_EMAIL,
recipient_list=[user.email],
fail_silently=False,
html_message=rendered)
the emails send fine but since it's sending from hi#myapp.com the email "From" alias in inboxes just shows up as "hi", and I'd like to make it more verbose so my recipients know who sent them the email ("Hi from AppName"). I don't see any field in send_mail docs (https://docs.djangoproject.com/en/2.1/topics/email/) for customizing how the "From" sender alias string appears (beyond the email itself) other than 'The “From:” header of the email will be the value of the SERVER_EMAIL setting'. does django's send_mail not support this (i.e., I need to rewrite this to using a sendgrid lib? https://github.com/sendgrid/sendgrid-python?) or is there a config setting in SendGrid where I can automatically set 'fromname'? thanks
Is that
Your example includes from_email=settings.DEFAULT_FROM_EMAIL. The docs say that the more verbose form is permitted, for example:
from_email="Hi from Appname <hi#myapp.com>",
You might also be able to change DEFAULT_FROM_EMAIL to the more verbose form. However the docs don't say whether this is supported or not, so I'm not sure whether this would cause problems somewhere.
I want to develop a simple web server using python to handle some simple http request. I have learn how to response the request, such as transferring html pages or transferring some other file. When I transfer a image file, a client use a browser to get the file, the url is like below:
http://114.212.82.104:8080/1.png
I set 'Content-Type = application/x-png'. But the browser directly download the file, and can not display in the browser. Not like the image below
https://www.baidu.com/img/bd_logo1.png
it can display in the browser. How to display the image in the browser?
Can someone help me?
and i know i can encode the image file into html page to fix it. code like below:
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
path = os.getcwd()+ self.path
if os.path.isfile(path):
with open(path,'rb') as fileTrans:
content = fileTrans.read().encode('base64').replace('\n','')
#self.sendContent(200, content)
self.send_response(200)
page = "<p>\"fef\"</p><img src=\"data:image/jpg;base64,{0}\"/>"
contentPage = page.format(content)
self.send_header('Content-Type', 'text/html')
self.send_header("Content-Length", str(len(contentPage)))
self.end_headers()
self.wfile.write(contentPage)
else:
self.sendContent(404,"file do not exists")
But I know there must be another way, i see the source code of URL(https://www.baidu.com/)
it just use
<img hidefocus="true" src="//www.baidu.com/img/bd_logo1.png" width="270" height="129"></div><a href="/" id="result_logo" onmousedown="return c({'fm':'tab','tab':'logo'})">
different from my page:
<p>"fef"</p><img src="data:image/jpg;base64,iVBORw0KGgoAAAANSUhEUgAAAcIAAAJYCAIAAAB+b3GqAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAvppVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMTMyIDc5LjE1OTI4NCwgMjAxNi8wNC8xOS0xMzoxMzo0MCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wTU09Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9tbS8iIHhtbG5zOnN0UmVmPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvc1R5cGUvUmVzb3VyY2VSZWYjIiB4bWxuczp4bXA9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC8iIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6ODg3NkM1Njg1MzVFMTFFNkE0NkJFNTEzMUFCNzc4RTMiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6ODg3NkM1Njc1MzVFMTFFNkE0NkJFNTEzMUFCNzc4RTMiIHhtcDpDcmVhdG9yVG9vbD0iOC4xLjMiPiA8eG1wTU06RG......
OK,I think I have solved this problem.
Just set the attribute - 'Content-Type' of header as 'image/png' instead of 'application/x-png'.
How can we set html tags inside the mail content while sending mail using mailgun api? When I send it, the tags are displaying as it is.
But in smtp, we can set it as , isBodyHtml=true
Here is the quick code example that can help you to send email in HTML format.
RestClient client = new RestClient();
client.BaseUrl = new Uri("https://api.mailgun.net/v3");
RestRequest request = new RestRequest();
client.Authenticator = new HttpBasicAuthenticator("api", "key-XXX");
request.AddParameter("domain","yourdomain.com", ParameterType.UrlSegment);
request.Resource = "{domain}/messages";
//request.AddParameter("from", "Mailgun Sandbox <postmaster#sandboxc.mailgun.org>");
request.AddParameter("from", "from#mail.com");
request.AddParameter("to", to);
request.AddParameter("subject", subject);
request.AddParameter("text", "Text view of this email is not supported. Please view this email in HTML format. Thank you.");
//This will help you to send email in HTML format
request.AddParameter("html", body);
request.Method = Method.POST;
RestResponse stat = client.Execute(request) as RestResponse;
Hope this helps.
You can put your html content (with the tags) in the 'html' parameter when calling the Mailgun API.
Taken from Mailgun homepage (the last line is what you are asking for):
POST /messages
from = 'App <me#myapp.io>'
to = 'bob#gmail.com'
subject = 'Hello'
text = 'Welcome to our amazing app!'
html = '<p>Welcome to our amazing app!</p>'
Hope this helps