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()
Related
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 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.
The registration of the website is for free: http://software.broadinstitute.org/gsea/login.jsp
I wrote this code to login the website based on some tutorials:
import requests
url = "http://software.broadinstitute.org/gsea/login.jsp"
# Fill in your details here to be posted to the login form.
payload = {
'j_username': 'xxx#gmail.com',
'j_password': 'password'
}
# Use 'with' to ensure the session context is closed after use.
s = request.session()
p = s.post(url, data=payload)
# print the html returned or something more intelligent to see if it's a successful login page.
print p, p.url, p.status_code
print 'is redirected: ', p.is_redirect
r = s.get("https://software.broadinstitute.org/gsea/msigdb/download_file.jsp?filePath=/resources/msigdb/6.2/msigdb_v6.2.xml")
# print r.text
print r, r.url, r.status_code
print 'is redirected: ', r.is_redirect
with open("lol.xml", "wb") as handle:
handle.write(r.content)
I am not sure if I have to fill in the password, because it is hidden?
The post command return me back a 200 OK, but I am still not logged in:
<Response [200]> http://software.broadinstitute.org/gsea/login.jsp 200
is redirected: False
<Response [200]> https://software.broadinstitute.org/gsea/login.jsp 200
is redirected: False
Ok, possible error sources are the payload with wrong dictionary keys.
The html code looks like this:
<form id="loginForm" name="loginForm" action="j_spring_security_check" method="POST">
<table border="0" class="bodyfont" cellpadding="5" cellspacing="5">
<tbody><tr>
<td colspan="2" align="left">Items marked with <font color="red">*</font> are required.</td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td><h3>Email: <font color="red">*</font> </h3></td>
<td><input id="email" type="text" name="j_username" value="">
<input id="password" type="hidden" name="j_password" value="password"></td>
</tr>
<tr>
<td> </td>
<td><input type="button" name="login" value="login" style="margin-top:10px;" onclick="validateForm()"></td>
</tr>
</tbody></table>
</form>
Do I miss something? Why is not it logged in?
As i mentioned in my comment it is a really good first step to look at the logs in the Network tab of Chrome when you want to login somewhere with requests. Your code doesn't work because you simply use the wrong url for your post-request! You also have some typos in your code e.g.: request.session() instead of requests.session().
import requests
login_url = "http://software.broadinstitute.org/gsea/j_spring_security_check"
url = "http://software.broadinstitute.org/gsea/index.jsp"
payload = {
'j_username': 'a4702585#nwytg.net',
'j_password': 'password'
}
with requests.Session() as session:
login = session.post(login_url, data=payload)
req = session.get(url)
In general i also doubt that looking at the response status code is a good way of figuring out if the login worked or not.
open a session
sent the post request including the payload (to the right url)
make a get request to simulate the redirect which happens automatically in the browser (again something you learn easily by using chrome network tab)
You can replace the url with any subdomain you want obviously...
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,
I'm trying to login to Myanimelist.net programmatically using urllib.
I'm not really sure what is happening. I'm not logging in correctly, as the code it returns isn't what I expect it to be. Not sure what the POST parameters should be or what I'm doing wrong. Looked at a bunch of similar stackoverflow questions regarding urllib login authentications but I can't figure it out.
This is the form:
<form action="http://myanimelist.net/login.php" id="loginForm" method="post" name="loginForm">
<table align="center" border="0" cellpadding="6" cellspacing="0">
<tbody>
<tr>
<td width="100"><strong>Username:</strong></td>
<td>
<input class="inputtext" id="loginUNAME" name="username"size="30" type="text" value="">
</td>
</tr>
<tr>
<td><strong>Password:</strong></td>
<td>
<input class="inputtext" name="password" size="30" type="password">
</td>
</tr>
<tr>
<td align="center" colspan="2">
<input name="cookie" type="checkbox" value="1"> Always stay logged in?
</td>
</tr>
<tr>
<td align="center" colspan="2"><input class="inputButton" name= "sublogin" type="submit" value="Login">
<input class="inputButton" name="register" onclick="document.location='http://myanimelist.net/register.php';" type="button" value="Register"></td>
</tr>
<tr>
<td align="center" colspan="2">
<a href="http://myanimelist.net/password.php">Forget Your
Password?</a>
</td>
</tr>
</tbody>
</table>
</form>
My login code:
import http.cookiejar
import urllib
from bs4 import BeautifulSoup
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
urllib.request.install_opener(opener)
url = 'http://myanimelist.net/login.php'
payload = {
'username' : '<username>',
'password' : '<password>',
'cookie' : '1',
'sublogin' : 'Login'
}
data = urllib.parse.urlencode(payload).encode('ascii')
request = urllib.request.Request(url=url, data=data)
response = urllib.request.urlopen(request)
html = response.read().decode('utf-8')
soup = BeautifulSoup(html)
print(soup.prettify())
and what I get is:
<html>
<head>
<META NAME="robots" CONTENT="noindex,nofollow">
<script>
(function(){function getSessionCookies(){cookieArray=new Array();var cName=/^\s?
incap_ses_/;var c=document.cookie.split(";");for(var i=0;i<c.length;i++){key=c[i
].substr(0,c[i].indexOf("="));value=c[i].substr(c[i].indexOf("=")+1,c[i].length)
;if(cName.test(key)){cookieArray[cookieArray.length]=value}}return cookieArray}f
unction setIncapCookie(vArray){try{cookies=getSessionCookies();digests=new Array
(cookies.length);for(var i=0;i<cookies.length;i++){digests[i]=simpleDigest((vArr
ay)+cookies[i])}res=vArray+",digest="+(digests.join())}catch(e){res=vArray+",dig
est="+(encodeURIComponent(e.toString()))}createCookie("___utmvc",res,20)}functio
n simpleDigest(mystr){var res=0;for(var i=0;i<mystr.length;i++){res+=mystr.charC
odeAt(i)}return res}function createCookie(name,value,seconds){if(seconds){var da
te=new Date();date.setTime(date.getTime()+(seconds*1000));var expires="; expires
="+date.toGMTString()}else{var expires=""}document.cookie=name+"="+value+expires
+"; path=/"}function test(o){var res="";var vArray=new Array();for(test in o){sw
itch(o[test]){case"exists":try{vArray[vArray.length]=encodeURIComponent(test+"="
+typeof(eval(test)))}catch(e){vArray[vArray.length]=encodeURIComponent(test+"="+
e)}break;case"value":try{vArray[vArray.length]=encodeURIComponent(test+"="+eval(
test).toString())}catch(e){vArray[vArray.length]=encodeURIComponent(test+"="+e)}
break;case"plugins":try{p=navigator.plugins;pres="";for(a in p){pres+=(p[a]["des
cription"]+" ").substring(0,20)}vArray[vArray.length]=encodeURIComponent("plugin
s="+pres)}catch(e){vArray[vArray.length]=encodeURIComponent("plugins="+e)}break;
case"plugin":try{a=navigator.plugins;for(i in a){f=a[i]["filename"].split(".");i
f(f.length==2){vArray[vArray.length]=encodeURIComponent("plugin="+f[1]);break}}}
catch(e){vArray[vArray.length]=encodeURIComponent("plugin="+e)}break}}vArray=vAr
ray.join();return vArray}var o={navigator:"exists","navigator.vendor":"value",op
era:"exists",ActiveXObject:"exists","navigator.appName":"value",platform:"plugin
",webkitURL:"exists","navigator.plugins.length==0":"value"};try{setIncapCookie(t
est(o));document.createElement("img").src="/_Incapsula_Resource?SWKMTFSR=1&e="+M
ath.random()}catch(e){img=document.createElement("img");img.src="/_Incapsula_Res
ource?SWKMTFSR=1&e="+e}})();
</script>
<script>
(function() {
var z="";var b="7472797B766172207868723B76617220743D6E6577204461746528292E676574
54696D6528293B766172207374617475733D227374617274223B7661722074696D696E673D6E6577
2041727261792833293B77696E646F772E6F6E756E6C6F61643D66756E6374696F6E28297B74696D
696E675B325D3D22723A222B286E6577204461746528292E67657454696D6528292D74293B646F63
756D656E742E637265617465456C656D656E742822696D6722292E7372633D222F5F496E63617073
756C615F5265736F757263653F4553324C555243543D363726743D373826643D222B656E636F6465
555249436F6D706F6E656E74287374617475732B222028222B74696D696E672E6A6F696E28292B22
2922297D3B69662877696E646F772E584D4C4874747052657175657374297B7868723D6E65772058
4D4C48747470526571756573747D656C73657B7868723D6E657720416374697665584F626A656374
28224D6963726F736F66742E584D4C4854545022297D7868722E6F6E726561647973746174656368
616E67653D66756E6374696F6E28297B737769746368287868722E72656164795374617465297B63
61736520303A7374617475733D6E6577204461746528292E67657454696D6528292D742B223A2072
657175657374206E6F7420696E697469616C697A656420223B627265616B3B6361736520313A7374
617475733D6E6577204461746528292E67657454696D6528292D742B223A2073657276657220636F
6E6E656374696F6E2065737461626C6973686564223B627265616B3B6361736520323A7374617475
733D6E6577204461746528292E67657454696D6528292D742B223A20726571756573742072656365
69766564223B627265616B3B6361736520333A7374617475733D6E6577204461746528292E676574
54696D6528292D742B223A2070726F63657373696E672072657175657374223B627265616B3B6361
736520343A7374617475733D22636F6D706C657465223B74696D696E675B315D3D22633A222B286E
6577204461746528292E67657454696D6528292D74293B6966287868722E7374617475733D3D3230
30297B706172656E742E6C6F636174696F6E2E72656C6F616428297D627265616B7D7D3B74696D69
6E675B305D3D22733A222B286E6577204461746528292E67657454696D6528292D74293B7868722E
6F70656E2822474554222C222F5F496E63617073756C615F5265736F757263653F535748414E4544
4C3D343436383430363736353433323532383538322C313135353632373036373830323435333434
33392C31373934323137333630323239353234373434352C333830353834222C66616C7365293B78
68722E73656E64286E756C6C297D63617463682863297B7374617475732B3D6E6577204461746528
292E67657454696D6528292D742B2220696E6361705F6578633A20222B633B646F63756D656E742E
637265617465456C656D656E742822696D6722292E7372633D222F5F496E63617073756C615F5265
736F757263653F4553324C555243543D363726743D373826643D222B656E636F6465555249436F6D
706F6E656E74287374617475732B222028222B74696D696E672E6A6F696E28292B222922297D3B";
for (var i=0;i<b.length;i+=2){z=z+parseInt(b.substring(i, i+2), 16)+",";}z = z.s
ubstring(0,z.length-1); eval(eval('String.fromCharCode('+z+')'));})();
</script></head>
<body>
<iframe style="display:none;visibility:hidden;" src="//content.incapsula.com/jsT
est.html" id="gaIframe"></iframe>
</body>
</html>
Any ideas about what I'm doing wrong?
The problem is on the following line:
response = urllib.request.urlopen(request)
You're submitting your request as a GET instead of POST which causes it to fail.
From the docs:
urllib.request.urlopen(url[, data][, timeout])
Open the URL url, which can be either a string or a Request object.
data may be a string specifying additional data to send to the server, or None if no such data is needed. Currently HTTP requests are the only ones that use data; the HTTP request will be a POST instead of a GET when the data parameter is provided. data should be a buffer in the standard application/x-www-form-urlencoded format. The urllib.parse.urlencode() function takes a mapping or sequence of 2-tuples and returns a string in this format.