使用rabbitmq實現異步發送郵件

# -*- coding: utf-8 -*-
# @Time    : 2019/8/21 17:35
# @Author  : Coderfly
# @Email   : [email protected]
# @File    : test.py

from smtplib import SMTP,SMTPException
from email.mime.text import MIMEText
from email.header import Header


class EMail(object):

    def __init__(self):
        self.init()

    def init(self):
        smtp = SMTP(host="smtp.163.com", port=25)
        smtp.login(user="xxxx", password="xxxx")
        self.smtp = smtp

    def send_email(self,receiver,content,sender="[email protected]",subject= '內部郵件'):
        print(receiver,"===",content)
        message = MIMEText(content, 'plain', 'utf-8')
        message['From'] = Header("行政部", 'utf-8')
        message['Subject'] = Header(subject, 'utf-8')
        self.smtp.sendmail(sender, receiver, message.as_string())

if __name__ == '__main__':
    s = EMail()
    s.send_email("[email protected]","過來")

receive.py

# -*- coding: utf-8 -*-
# @Time    : 2019/8/21 18:07
# @Author  : Coderfly
# @Email   : [email protected]
# @File    : receive.py
import pika
import json
from send_email.email_util import EMail
email = EMail()
connection = pika.BlockingConnection(pika.ConnectionParameters(host="192.168.57.25",port=5672))
channel = connection.channel()
channel.queue_declare(queue="email")
def callback(ch, method, properties, body):
    email_message = json.loads(body)
    email.send_email(**email_message)
channel.basic_consume(on_message_callback=callback,queue="email",auto_ack=True)

channel.start_consuming()

send.py

# -*- coding: utf-8 -*-
# @Time    : 2019/8/21 17:34
# @Author  : Coderfly
# @Email   : [email protected]
# @File    : send.py
import pika
import json
connection = pika.BlockingConnection(pika.ConnectionParameters(host="192.168.57.25",port=5672))
channel = connection.channel()
channel.queue_declare(queue="email")
email_message = {
    "receiver":"[email protected]",
    "content":"來辦公室一趟!"
}
channel.basic_publish(exchange='',
                      routing_key='email',
                      body=json.dumps(email_message))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章