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

Viewed 26

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;'>
                                            &reg; 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;
1 Answers

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
Related