iT邦幫忙

0

gmail flask_mail Connection unexpectedly closed

  • 分享至 

  • xImage

大家好,我用flask_mail 寄發了mail,並設定了排程,信件有成功寄出,可是最後會報錯` * Serving Flask app 'email true' (lazy loading)

  • Environment: production
  • Debugger is active! * Debugger PIN: 965-935-309
    Job "job_cron (trigger: cron[day='*', hour='21', minute='3'], next run at: 2022-07-22 21:03:00 CST)" raised an exception
    Traceback (most recent call last):
    File "C:\Users\yayaa\AppData\Local\Programs\Python\Python310\lib\site-packages\apscheduler\executors\base.py", line 125, in run_job
    retval = job.func(job.args, **job.kwargs)
    File "C:\Users\yayaa\AppData\Local\Temp\Rar$DIa14768.32153\email true.py", line 54, in send_mail
    Thread(target=mail.send(msg)).start()
    File "C:\Users\yayaa\AppData\Local\Programs\Python\Python310\lib\site-packages\flask_mail.py", line 491, in send
    with self.connect() as connection:
    File "C:\Users\yayaa\AppData\Local\Programs\Python\Python310\lib\site-packages\flask_mail.py", line 144, in enter
    self.host = self.configure_host()
    File "C:\Users\yayaa\AppData\Local\Programs\Python\Python310\lib\site-packages\flask_mail.py", line 165, in configure_host
    host.login(self.mail.username, self.mail.password)
    File "C:\Users\yayaa\AppData\Local\Programs\Python\Python310\lib\smtplib.py", line 739, in login
    (code, resp) = self.auth(
    File "C:\Users\yayaa\AppData\Local\Programs\Python\Python310\lib\smtplib.py", line 642, in auth
    (code, resp) = self.docmd("AUTH", mechanism + " " + response)
    File "C:\Users\yayaa\AppData\Local\Programs\Python\Python310\lib\smtplib.py", line 432, in docmd
    return self.getreply()
    File "C:\Users\yayaa\AppData\Local\Programs\Python\Python310\lib\smtplib.py", line 405, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
    smtplib.SMTPServerDisconnected: Connection unexpectedly closed
    Job "job_cron (trigger: cron[day='
    ', hour='21', minute='3'], next run at: 2022-07-22 21:03:00 CST)" raised an exception
    Traceback (most recent call last):
    File "C:\Users\yayaa\AppData\Local\Programs\Python\Python310\lib\site-packages\apscheduler\executors\base.py", line 125, in run_job
    retval = job.func(*job.args, **job.kwargs)
    File "c:\Users\yayaa\AppData\Local\Temp\Rar$DIa14768.32153\email true.py", line 54, in send_mail
    Thread(target=mail.send(msg)).start()
    File "C:\Users\yayaa\AppData\Local\Programs\Python\Python310\lib\site-packages\flask_mail.py", line 491, in send
    with self.connect() as connection:
    File "C:\Users\yayaa\AppData\Local\Programs\Python\Python310\lib\site-packages\flask_mail.py", line 144, in enter
    self.host = self.configure_host()
    File "C:\Users\yayaa\AppData\Local\Programs\Python\Python310\lib\site-packages\flask_mail.py", line 165, in configure_host
    host.login(self.mail.username, self.mail.password)
    File "C:\Users\yayaa\AppData\Local\Programs\Python\Python310\lib\smtplib.py", line 739, in login
    (code, resp) = self.auth(
    File "C:\Users\yayaa\AppData\Local\Programs\Python\Python310\lib\smtplib.py", line 642, in auth
    (code, resp) = self.docmd("AUTH", mechanism + " " + response)
    raise SMTPServerDisconnected("Connection unexpectedly closed") smtplib.SMTPServerDisconnected: Connection unexpectedly closed`
    程式碼如下
from flask import Flask
import pymysql
from flask_mail import Mail,Message
from flask_apscheduler import APScheduler
from apscheduler.schedulers.background import BackgroundScheduler
from flask import current_app 
import time
from threading import Thread
import smtplib

app = Flask(__name__)


app.config.update(
    MAIL_SERVER = 'smtp.gmail.com',
    MAIL_PORT = '587',
    MAIL_USE_TLS = True,
    MAIL_USERNAME = '',
    MAIL_PASSWORD=  '',
    MAIL_DEFAULT_SENDER= ''
)
mail = Mail(app)
def db_init():
    with app.app_context():
      db = pymysql.connect(
        host = 'ec2-34-208-156-155.us-west-2.compute.amazonaws.com',
        user = '',
        password = '',
        database='metaage_sales',
        port = 3306
    )
      cursor = db.cursor(pymysql.cursors.DictCursor)
      return db, cursor

class Config(object):
    SCHEDULER_API_ENABLED = True
    SCHEDULER_TIMEZONE = 'Asia/Taipei'
app.config.from_object(Config())
scheduler = APScheduler(BackgroundScheduler(timezone='Asia/Taipei'))


def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)
 
def send_mail():
    with app.app_context():
      db,cursor=db_init()
      cursor.execute('SELECT `me_boss`.`PO_Number`,`me_IT`.`Email`,TIMESTAMPDIFF(DAY, now(),`Renewal_Date`) AS daytype FROM `metaage_sales`.`me_boss`,`me_IT`HAVING daytype<=30 AND daytype>0;')
      detail = cursor.fetchall()
      for i in detail:
          msg = Message(subject='ERP',body='Hello ' + str(i['PO_Number'])+ 'Thanks For using our services.',recipients=[str(i['Email'])])
                #msg.subject = 'Resr'
          Thread(target=mail.send(msg)).start()
          db.commit()
          cursor.close()
    
      db.close()    
      return 'Sent!!'

def server_smtp_reconnect(self):
		"""
		Disconnect from the remote SMTP server and then attempt to open
		a new connection to it.

		:return: The reconnection status.
		:rtype: bool
		"""
		if self.smtp_connection:
			try:
				self.smtp_connection.quit()
			except smtplib.SMTPServerDisconnected:
				pass
			self.smtp_connection = None
		while self.server_smtp_connect() != ConnectionErrorReason.SUCCESS:
			self.tab_notify_status('Failed to reconnect to the SMTP server')
			if not self.process_pause(True):
				return False
		return True

if __name__ == "__main__":
    scheduler.add_job(func=send_mail,id='job_cron', trigger='cron', day='*', hour=21 ,minute=3)
    scheduler.start()
    app.run(debug=True)
    while True:
        print(time.time())
        time.sleep(5)
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答