Python: Create mail - display mail but not send it - smtplib + MIMEmultipart + Outlook - python

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,

Related

HTML table to outlook via python

I need to send an HTML table to outlook via python I tried this code but it isn't working it send an empty mail to me
msg = MIMEMultipart()
msg['Subject'] = "subject"
msg['From'] = "from.com"
msg['To'] = ', '.join(email_list)
html = """table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th>DG Lead</th>
</tr>
</thead>
<tbody>
<tr>
<td>Krishnamurthy Ramamurthy</td>
<td>324</td>
>
<tr> """
msg.HTMLBody=html
s = smtplib.SMTP(SERVER)
s.sendmail("from.com", email_list, msg.as_string())
s.quit()
this should work for you , using the Gmail SMTP server
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Set up the message parameters
msg = MIMEMultipart()
msg['From'] = 'From#gmail.com'
msg['To'] = 'TO#hotmail.com'
msg['Subject'] = 'Test HTML Email'
# Create the HTML message
html = """<html><body><p>This is a test HTML email!</p><table border="1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
</tr>
</table></body></html>"""
msg.attach(MIMEText(html, 'html'))
# Send the message via Gmail SMTP server
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('youremail(gmail)', '[app password][1]') # Replace with your actual password
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()

Executing Python Scripts for sending email using smtp fails from PHP shell_exec

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

HTML IFrame not working when being used in Gmail

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.

How to send AMP Email from Python? How is it technically different from Normal Email

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

How do I retrieve the server address via a button

I execute my script in command line.
When I execute ./script.py server_adress param2 param3 param4 it opens a page with html form and a button, when we type on the button, I want to retrieve this server address.
that's a part of the code of the script.py :
import os, sys, platform, getpass, tempfile
import webbrowser
import string
import json
def main( server_IP, code_name, code_version, install_path):
template = open('scriptHmtl.phtml').read()
contenu = string.Template(template).substitute(
code_name = code_name,
code_version = code_version,
install_path = install_path,
os = user_os,
user_name = user_login
)
f = tempfile.NamedTemporaryFile(prefix='/tmp/info.html', mode='w', delete=False)
f.write(contenu)
f.close()
webbrowser.open(f.name)
if __name__ == "__main__":
server_IP = sys.argv[1]
code_name = sys.argv[2]
code_version = sys.argv[3]
install_path = sys.argv[4]
user_os = sys.platform
sys.argv.append(user_os)
user_login = getpass.getuser()
sys.argv.append(user_login)
config_file = open("config.txt", "w")
json.dump(sys.argv, config_file)
main(server_IP, code_name, code_version, install_path)
and here, the code html to get the address , scriptHtml.py
<html>
<body>
App: ${code_name}<br/><br/>
cv: ${code_version}<br/><br/>
path install: ${install_path}<br/><br/>
<form name="Data" method="get" action="http://localhost:8000/cgi/scriptGet.py">
Name: <input type="text" name="name"><br/><br/>
First name: <input type="text" name="fn"/><br/><br/>
Mail: <input type="text" name="mail"/><br/><br/>
<input type="submit" value="OK"/>
</form>
</body>
</html>
action="http://localhost:8000/cgi/scriptGet.py" -> I think the problem is here.
What you really want to do here is use a proper Python Web Framework.
CGI went out of fasion decdaes ago?
Example: (Using circuits):
#!/usr/bin/env python
"""Forms
A simple example showing how to deal with data forms.
"""
from circuits.web import Server, Controller
FORM = """
<html>
<head>
<title>Basic Form Handling</title>
</head>
<body>
<h1>Basic Form Handling</h1>
<p>
Example of using
circuits and its
<b>Web Components</b> to build a simple web application that handles
some basic form data.
</p>
<form action="/save" method="POST">
<table border="0" rules="none">
<tr>
<td>First Name:</td>
<td><input type="text" name="firstName"></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" name="lastName"></td>
</tr>
<tr>
<td colspan=2">
<input type="submit" value="Save">
</td>
</tr>
</table>
</form>
</body>
</html>"""
class Root(Controller):
def index(self):
"""Request Handler
Our index request handler which simply returns a response containing
the contents of our form to display.
"""
return FORM
def save(self, firstName, lastName):
"""Save Request Handler
Our /save request handler (which our form above points to).
This handler accepts the same arguments as the fields in the
form either as positional arguments or keyword arguments.
We will use the date to pretend we've saved the data and
tell the user what was saved.
"""
return "Data Saved. firstName={0:s} lastName={1:s}".format(
firstName, lastName
)
app = Server(("0.0.0.0", 8000))
Root().register(app)
app.run()
Disclaimer: I'm the developer of circuits.
NB: There are many other good Python Web Frameworks:
flask
bottle
Django
... etc ...
contenu = string.Template(template).substitute(
code_name = code_name,
code_version = code_version,
install_path = install_path,
os = user_os,
user_name = user_login
server_IP = http:8000/cgi/scriptGet.py
)
scriptHtml.py
<form name="Data" method="get" action="${server_IP}">
that is something like that ?

Categories

Resources