I have a script which automatically sends mail to users. Here's the script - even though I don't think it's relevant to the question:
import smtplib
import imghdr
from email.message import EmailMessage
EMAIL_ADDRESS = email
EMAIL_PASSWORD = noIAmNotShowingYouMyPassword
userEmail = email
msg = EmailMessage()
msg['Subject'] = 'Title'
msg['From'] = EMAIL_ADDRESS
msg['To'] = userEmail
msg.set_content('This is a plain text email')
html = open('email.html', 'r').read().format(userEmail = userEmail)
print(html)
msg.add_alternative(html, subtype='html')
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
smtp.send_message(msg)
The email.html file is as follows:
<body>
<div style="font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;font-size: large; align-items: center;align-content: center;text-align: left;border: 100px;box-shadow: 20px;">
<h3 style="font-weight: bold;">Hey there, {userEmail}!
<h3>
<p>Want an appeal? Fill the form below, or click the button to go to the Google Form website.</p>
<button href="googleFormLink">Head to the site</button>
<iframe src="googleFormEmebedLink" width="700" height="520" frameborder="0" marginheight="0" marginwidth="0">Loading…</iframe>
</div>
</body>
</html>
My issue is the <iframe src="googleFormEmebedLink" width="700" height="520" frameborder="0" marginheight="0" marginwidth="0">Loading…</iframe>, which doesn't show up.
The button does though, however it doesn't work.
I suspect it's security matter on Google's side, but I want to confirm. Also, I need a way to fix this issue.
I've checked on an online HTML viewer, it worked perfectly fine. Below are images showing the Gmail VS the HTML Viewers' results.
Related
I have a pandas dataframe that I am sending to myself via email.
I am able to control the font size of the heading and body, however the dataframe itself is its default size which is a bit small for me.
How do I increase the font size of the table that is being sent?
Here is the html part of code I am using:
html = """\
<html>
<head></head>
<h1 style="color:red;font-size:25px;">This is My Header</h1>
<p style="width:50px;height:50px;">
<body>
{0}
</body>
</p>
</html>
""".format(df3.to_html())
consumptions = MIMEText(html, 'html')
msg.attach(consumptions)
Any suggestions?
I'm trying to execute a python script from PHP for sending an email using SMTP from python. When I execute it manually it's working fine
but not from PHP getting an SSL certificate error, pls help me on a fix.
I'm not going to use PHP for sending an email, need solutions only from python.
Using Xampp server in ubuntu 20.4 LTS.
Getting the below error while executing from PHP:
[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer ``````certificate (_ssl.c:1131)
<class 'ssl.SSLCertVerificationError'>
Sample Code python:
from datetime import date
import smtplib
import email
from email import encoders
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import ssl
import argparse, sys, os
try:
parser = argparse.ArgumentParser()
parser.add_argument('-username', action='store',
dest='username', required=True, help='')
parser.add_argument('-fullname', action='store',
dest='fullname', required=False, help='')
parser.add_argument('-email', action='store',
dest='email', required=False, help='')
inputs = parser.parse_args()
email_id = inputs.email
fullname = inputs.fullname
username = inputs.username
"""
class email_operation:
'''
This Class used to trigger functions for tasks Email
'''
def __init__(self):
test = ''
def send_regConfirmation(self, username, email_id, fullname):
"""
msg = MIMEMultipart("alternative")
msg["Subject"] = "Welcome to Madurai E-Cart Shopping"
msg["From"] = ""
msg["To"] = email_id
# filename = "document.pdf"
port = 587 # For starttls
smtp_server = "smtp-mail.outlook.com"
sender_email = ""
receiver_email = email_id
password = ""
todays_date = date.today()
html = """<!DOCTYPE html>
<html lang='en' xmlns='http://www.w3.org/1999/xhtml' xmlns:o='urn:schemas-microsoft-com:office:office'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width,initial-scale=1'>
<meta name='x-apple-disable-message-reformatting'>
<title></title>
<style>
table,
td,
div,
h1,
p {
font-family: Arial, sans-serif;
}
</style>
</head>
<body style='margin:0;padding:0;'>
<table role='presentation'
style='width:100%;border-collapse:collapse;border:0;border-spacing:0;background:#ffffff;'>
<tr>
<td align='center' style='padding:0;'>
<table role='presentation'
style='width:602px;border-collapse:collapse;border:1px solid #cccccc;border-spacing:0;text-align:left;'>
<tr>
<td align='center' style='padding:40px 0 30px 0;background:#70bbd9;'>
<img src='https://www.picng.com/upload/welcome/png_welcome_54186.png' alt='' width='300'
style='height:auto;display:block;' />
</td>
</tr>
<tr>
<td style='padding:36px 30px 42px 30px;'>
<table role='presentation'
style='width:100%;border-collapse:collapse;border:0;border-spacing:0;'>
<tr>
<td style='padding:0 0 36px 0;color:#153643;'>
<h1 style='font-size:24px;margin:0 0 20px 0;font-family:Arial,sans-serif;'>
Welcome to Madurai E-Cart Shopping</h1>
<p
style='margin:0 0 12px 0;font-size:16px;line-height:24px;font-family:Arial,sans-serif;'>
<h4>Hi """+fullname+""",</h4>
Welcome to Madurai E-Cart Shopping, your username is """+username+""".</br>
You have lot to explore and experience, dive into our site using below link.
</p>
<p
style='margin:0;font-size:16px;line-height:24px;font-family:Arial,sans-serif;'>
<a href='http://localhost/mdu_ecommerce'
style='color:#ee4c50;text-decoration:underline;'>Experience Here</a>
</p>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td style='padding:30px;background:#ee4c50;'>
<table role='presentation'
style='width:100%;border-collapse:collapse;border:0;border-spacing:0;font-size:9px;font-family:Arial,sans-serif;'>
<tr>
<td style='padding:0;width:50%;' align='left'>
<p
style='margin:0;font-size:14px;line-height:16px;font-family:Arial,sans-serif;color:#ffffff;'>
® Madurai E-Cart Shopping, """+str(todays_date.year)+"""<br />
</p>
</td>
<td style='padding:0;width:50%;' align='right'>
<table role='presentation'
style='border-collapse:collapse;border:0;border-spacing:0;'>
<tr>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
"""
part = MIMEText(html, "html")
msg.attach(part)
"""
with open(filename, "rb") as attachment:
part = MIMEBase("application", "octet-stream")
part.set_payload(attachment.read())
"""
encoders.encode_base64(part)
context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
server.ehlo() # Can be omitted
server.starttls(context=context)
server.ehlo() # Can be omitted
server.login(sender_email, password)
server.sendmail(sender_email, receiver_email, msg.as_string())
except Exception as e:
print(e)
exc_type, exc_obj, exc_tb = sys.exc_info()
fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
print(exc_type, fname, exc_tb.tb_lineno)
# obj = email_operation()
# obj.send_regConfirmation(username='meenaatchi', email_id="meenaatchi141996#gmail.com", fullname="Meenaatchi K N")
Php:
$exec_cmd = 'python3 {path}/send_email.py -username "{username}" -fullname "{fullname}" -email "{test#test.com}"
';
$command = escapeshellcmd($exec_cmd);
$mail = shell_exec($command);
echo $mail;
I fixed it by adding the below line for the context
context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
I am trying to understand what is AMP Email and also understand how I can send it from something like Pyhton/NodeJs/Ruby.
Currently in Python I send email as below:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from = "from#email.address"
to = "to#email.address"
msg = MIMEMultipart('alternative')
msg['Subject'] = "AMP Email"
msg['From'] = from
msg['To'] = to
#Email body.
plain_text = "Hi,\nThis is the plain text version of this Email.\nHere is a link that is for testing:\nhttps://amp.dev/documentation/guides-and-tutorials/start/create_email/?format=email"
html_amp = """\
<html amp4email>
<head>
<meta charset="utf-8">
<script async src="https://cdn.ampproject.org/v0.js"></script>
<style amp4email-boilerplate>body{visibility:hidden}</style>
<style amp-custom>
h1 {
margin: 1rem;
}
</style>
</head>
<body>
<p>Hi!<br>
<h1>Hello, I am an AMP EMAIL!</h1>
</p>
</body>
</html>
"""
part1 = MIMEText(plain_text, 'plain')
part2 = MIMEText(html_amp, 'html')
msg.attach(part1)
msg.attach(part2)
s = smtplib.SMTP('localhost')
s.sendmail(me, you, msg.as_string())
s.quit()
The above approach however isn't working.
I am trying to understand:
What is the key advantage AMP brings to Email?
How is it technically different?
Can everyone send AMP Mail?
Does it have any difference from normal emails?
I think you are almost there. You seem to not have fully understand what AMP Email is. A quick corrected version of your code will be as below, you have given AMP content in html mimetype:
#Main Mimetype
msg = MIMEMultipart('alternative')
msg['Subject'] = "AMP Email"
msg['From'] = from
msg['To'] = to
#Email body.
plain_text = "Hi,\nThis is the plain text version of this Email.\nHere is a link that is for testing:\nhttps://amp.dev/documentation/guides-and-tutorials/start/create_email/?format=email"
html = """\
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<p>Hi!<br>
<h1>Hello, I am an HTML MAIL!</h1>
</p>
</body>
</html>
"""
html_amp = """\
<html amp4email>
<head>
<meta charset="utf-8">
<script async src="https://cdn.ampproject.org/v0.js"></script>
<style amp4email-boilerplate>body{visibility:hidden}</style>
<style amp-custom>
h1 {
margin: 1rem;
}
</style>
</head>
<body>
<p>Hi!<br>
<h1>Hello, I am an AMP EMAIL!</h1>
</p>
</body>
</html>
"""
#Important: Some email clients only render the last MIME part, so it is
#recommended to place the text/x-amp-html MIME part before the text/html.
part1 = MIMEText(plain_text, 'plain')
part2 = MIMEText(html_amp, 'x-amp-html')
part3 = MIMEText(html, 'html')
msg.attach(part1)
msg.attach(part2)
msg.attach(part3)
s = smtplib.SMTP('localhost')
s.sendmail(me, you, msg.as_string())
s.quit()
To answer your questions:
In-Short:
AMP for Email lets email senders use AMP in their email messages to support many new features. AMP Email can contain interactive elements, like image carousels, updated contact via API, and the ability to submit a form without leaving the inbox.
Technical Difference from HTML Email:
AMP email is just an extension of a normal HTML email, which is a multipart MIME message. Most of the email you send or receive on Gmail, Outlook etc are multipart MIME messages, even though you may not be aware. It means, the email consists of multiple parts. Usually a text part and an HTML part.
Support:
Most desktop & web based email readers are HTML-capable and display the HTML part of the multipart message. However, some mobile readers might be limited and display only the text part of the multipart MIME message. With the advent of AMP, now’ll have one more part that is the AMP part. Email readers that has capability to support AMP will pick that part and rest will fall back to the HTML version. Gmail, Outlook, Yahoo & Mail.ru has already announced support for AMP Email.
Example:
(An example AMP Email will look as below)
From: Person A <persona#example.com>
To: Person B <personb#example.com>
Subject: An AMP email!
Content-Type: multipart/alternative; boundary="001a114634ac3555ae05525685ae"
--001a114634ac3555ae05525685ae
Content-Type: text/plain; charset="UTF-8"; format=flowed; delsp=yes
Hello World in plain text!
--001a114634ac3555ae05525685ae
Content-Type: text/x-amp-html; charset="UTF-8"
<!doctype html>
<html ⚡4email>
<head>
<meta charset="utf-8">
<style amp4email-boilerplate>body{visibility:hidden}</style>
<script async src="https://cdn.ampproject.org/v0.js"></script>
</head>
<body>
Hello World in AMP!
</body>
</html>
--001a114634ac3555ae05525685ae--
Content-Type: text/html; charset="UTF-8"
<span>Hello World in HTML!</span>
--001a114634ac3555ae05525685ae
Key points to keep in mind:
Some email clients will only render the last MIME part. Place the text/x-amp-html MIME part _before _the text/html MIME part.
A Html fallback content is compulsory as many clients don’t support AMP. Above that, AMP part is removed when the email is forwarded.
AMP email can only be send from a whitelisted email. You can do that by following this documentation. https://developers.google.com/gmail/ampemail/register
I am currently trying to write a function which will create a mail and then displayed it through Outlook.
Like this the user will be able to create and see his new mail under Outlook, and just decide to click on Send or not.
I struggle to find an attribute to smtplib, or an attribute to Mimemultipart like smtplib.display() or
msg = MIMEMultipart('alternative')
msg = email.message.Message()
msg.display(True).
I already succesfully create and send automatically mail with smtplib. What I can't find on the web, is this attribute to display the crated mail.....
What I have:
def createEmailConfirmation():
email_content = """\
<!DOCTYPE html><html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
</head>
<body>
<div class="table-responsive">
<table class="table table-bordered m-b-0">
<thead>
<tr>
<th> Title </th>
</tr>
</thead>
<tbody>
<tr>
<td> Confirmation </td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
"""
msg = MIMEMultipart('alternative')
msg = email.message.Message()
msg['Subject'] = 'Confirmation Mail'
toaddr = ['useraddressmail#test.com']
bcc = ['']
cc = ['']
fromaddr = ''other_useraddressmail#test.com'
toaddrs = toaddr + cc + bcc
password = "password"
msg.add_header('Content-Type', 'text/html')
msg.set_payload(email_content)
s = smtplib.SMTP('**.***.**.**')
s.set_debuglevel(False) # show communication with the server
msg.display
I think it something really easy, that will only fit In one line but I can't find it...
Best Regards,
from django.core.mail import EmailMultiAlternatives
def mail_fun(confirmation_id):
subject, from_email, to = 'hello', 'manikandanv3131#gmail.com', 'mani#ithoughtz.com'
text_content = 'This is an important message.'
html_content = """<a style="display: block;position: relative;background-color:
#2B7ABD;width: 144px;height: 30px;text-align: center;text-decoration: none;color:
white;font-size: 14px;top: 49px;border-radius: 4px;margin-left: 178px;"
href="http://127.0.0.1:8000/confirm_mail/?confirmation_id=" + confirmation_id ><span
style="display:block;position: relative;top: 8px;">Confirm Email adress</span></a>
"""
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
mail_fun('1234567890')
Problem here is, text content not is not displaying in the mail and the dynamic link in the code is also not working. Any help will be appreciated
String concatenation will not work inside strings, you need to set up your strings correctly. In fact, you should actually be using templates for this, rather than having HTML inside your view.
Create a template for your email, save it under the templates directory of any application that is in INSTALLED_APPS:
<html>
<head>
<title>Email</title>
</head>
<style>
div.link {
display: 'block';
position: 'relative';
background-color: '#2B7ABD';
width: 144px;
height: 30px;
text-align: center;
text-decoration: none;
color: white;
font-size: 14px;
margin-top: 49px;
border-radius: 4px;
margin-left: 178px;
}
</style>
<body>
<div class="link">
Confirm Email adress
</div>
</body>
</html>
In your view code:
from django.template.loader import render_to_string
from django.core.mail import EmailMultiAlternatives
def send_email(id=None,
subject='hello',
from_email='manikandanv3131#gmail.com',
to='mani#ithoughtz.com'):
text_content = 'This is an important message.'
html_content = render_to_string('html_email.html', {'id': id})
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
Keep in mind that if a mail client shows the HTML part, it will not show the alternative plain text part. You would have to view the source of the email to see both parts.
If this is something you will be doing often, you can use django-templated-email which offers more flexibility.