执行Python脚本以使用SMTP从php shell_exec发送电子邮件失败

发布于 2025-01-29 05:18:25 字数 7970 浏览 0 评论 0原文

我正在尝试从PHP执行Python脚本,以使用Python的SMTP发送电子邮件。当我手动执行它时,它可以正常工作,

但不能从PHP遇到SSL证书错误,请帮助我解决问题。 我不会使用PHP发送电子邮件,只需要Python的解决方案。

在Ubuntu 20.4 LTS中使用XAMPP服务器。

从PHP执行时获取以下错误:

[ssl:cetide_verify_failed]证书验证失败:无法获得本地发行者`````````````````````````````````` < class'Ssl.sslcertverificationerror'>

示例代码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="[email protected]", fullname="Meenaatchi K N")

php:php:

$exec_cmd = 'python3 {path}/send_email.py -username "{username}" -fullname "{fullname}" -email "{[email protected]}"
';
$command = escapeshellcmd($exec_cmd);
$mail = shell_exec($command);
echo $mail;

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="[email protected]", fullname="Meenaatchi K N")

Php:

$exec_cmd = 'python3 {path}/send_email.py -username "{username}" -fullname "{fullname}" -email "{[email protected]}"
';
$command = escapeshellcmd($exec_cmd);
$mail = shell_exec($command);
echo $mail;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柒七 2025-02-05 05:18:25

我通过在上下文中添加以下行来修复它

context = ssl.create_default_context()
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文