Hai..
Berikut ini cara mengirim email ketika receive message dari RabbitMQ.
Asumsi saya kita sudah sukses menginstall RabbitMQ.
Langkah pertama di Python, install librari nya:
python -m pip install pika --upgrade
Lalu kita membuat sender dulu sender.py:
#!/usr/bin/env python
import pika
import sys
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
message = ' '.join(sys.argv[1:]) or "Hello World!"
channel.basic_publish(exchange='',
routing_key='hello',
body= message)
print(" [x] Sent %r " % message)
connection.close()
setelah membuat sendernya, kita buat komponen module mailconfig.py
*kita menggunakan mailtrap pada case ini.
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
port = 2525
smtp_server = "smtp.mailtrap.io"
login = "05fb082aaaaaaa" # paste your login generated by Mailtrap
password = "6a9669aaaaaaa" # paste your password generated by Mailtrap
lalu buat file untuk mengirim email, beri nama receive.py
#!/usr/bin/env python
import pika, sys, os
import mailconfig
sender_email = "mailtrap@example.com"
receiver_email = "new@example.com"
def main():
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='hello')
def callback(ch, method, properties, body):
part1 = mailconfig.MIMEText(str(body.decode()), "html")
message = mailconfig.MIMEMultipart("alternative")
message["Subject"] = "multipart test"
message["From"] = sender_email
message["To"] = receiver_email
message.attach(part1)
with mailconfig.smtplib.SMTP("smtp.mailtrap.io", 2525) as server:
server.login(mailconfig.login, mailconfig.password)
server.sendmail(
sender_email, receiver_email, message.as_string()
)
print(" [x] Received %r" % body)
channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print('Interrupted')
try:
sys.exit(0)
except SystemExit:
os._exit(0)
Setelah selesai semua, kita jalankan di dua terminal.
terminal pertama:
python receive-send.py
terminal kedua:
py send.py hi apa kabar!
Jika sukses, akan ada email baru di mailtrap.io
Terimakasih, semoga bermanfaat.