在cPanel上使用Python发送电子邮件

时间:2019-03-03 00:17:11

标签: python cgi cpanel

我正在组建一个提供电子邮件服务的网站,但是我无法使用登录功能。我很烦恼,发现直到那时其他所有东西都可以运行,并且只有到那时代码才停止运行。现在以其形式存在的代码可以在我的计算机上运行,​​只有当我将其放入cPanel时,它才能停止运行。到底是怎么回事?

应该注意,我正在cPanel的cgi-bin中运行python。以前的python起作用了,只是服务器给了我一个问题。

#!/usr/bin/python3

print("Content-type: text/html\n\n")

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

class Mailer(object):

    def __init__(self, address, password):
    self.address = address
    self.password = password
    self.signature = None
    self._refresh_connection()

def __enter__(self):
    return self

def __exit__(self, errtype, errinst, traceback):
    self.close()

def _refresh_connection(self):
    self.server = smtplib.SMTP('smtp.gmail.com', port=587)
    self.server.ehlo()
    self.server.starttls()
    self.server.login(self.address, self.password) #This line is where it ceases to run

def close(self):
    self.server.close()

def add_signature(self, data, type='plain'):
    self.signature = MIMEText(data, type)

def make_email(self, to, msg, subject=None, type='plain'):
    mail = MIMEMultipart()
    mail["To"] = to
    mail['From'] = self.address
    if subject is not None:
        mail['Subject'] = subject
    mail.attach(MIMEText(msg, type))
    if self.signature is not None:
        mail.attach(self.signature)
    return mail

def send(self, to, msg, subject=None, type='plain'):
    print('sending emails')
    print('to:', to, ', from:', self.address)
    email = self.make_email(to, msg, subject, type)
    self.server.sendmail(self.address, to, email.as_string())
myEmail = Mailer('myEmail','myPassword')
myEmail.send('recipient','This is my message')

0 个答案:

没有答案