Send a message to a channel when new emails arrive in an email account

Hi there, is there an app out there for Rocket Chat that can send a message to a channel whenever a new email arrives in a specified email account?

And better yet, can send a message to a channel whenever an email arrives in a specified email account matching specific subject or body text?

1 Like

Hey,

we use this simple Python script to automate this task:

#!/usr/bin/env python3

import email
import imaplib
import sys
from email.header import decode_header

import requests

from secrets import *

imap = imaplib.IMAP4_SSL("smtp.example.com")
imap.login(username, password)

status, messages = imap.select("INBOX")

if status != "OK":
    print("Could not connect to INBOX")
    sys.exit(1)

count = int(messages[0])

for i in range(1, count + 1):
    # Fetch only the headers, the body does no matter for us
    res, msg = imap.fetch(str(i), "(RFC822.HEADER)")

    if res != "OK":
        print("Error with message object:", res, msg)
        continue

    for response in msg:
        if isinstance(response, tuple):
            msg = email.message_from_bytes(response[1])

            # Decode the subject header and reassemble afterwards
            subject_header = decode_header(msg["Subject"])
            subject = ""
            for value, encoding in subject_header:
                if isinstance(value, bytes):
                    if encoding is not None:
                        subject += value.decode(encoding, errors="ignore")
                    else:
                        subject += value.decode("L1", errors="ignore")
                else:
                    subject += value

            # Decode the from header and reassemble afterwards
            from_header = decode_header(msg.get("From"))
            sender = ""
            for value, encoding in from_header:
                if isinstance(value, bytes):
                    if encoding is not None:
                        sender += value.decode(encoding, errors="ignore")
                    else:
                        sender += value.decode("L1", errors="ignore")
                else:
                    sender += value

            mail = {
                "text": f"Neue Email von {sender}:",
                "attachments": [
                    {
                        "text": subject
                    }
                ]
            }
            requests.post(json=mail, url=rocket_hook)

    imap.store(str(i), '+FLAGS', '\\Deleted')

imap.expunge()
imap.close()
imap.logout()

Please note, that this script does only work if every processed email gets deleted (the script does that). So you will need to setup a shadow copy email account for this script to run on.

Hello,.

Thanks for sharing this but I have two questions.

  1. How do you execute the script? Do you place it at the webhook script ? Forgive my naiveness here but I wasn’t sure if one can actually run a python script to facilitate a webhook. The other option might be to execute the script as a crontab or celery task. Would you please clarify if it’s the former or the latter?

  2. Is it at all possible to send the emails into the omnichannel as opposed to the main channels?

Thank you. Any insights or suggestions will be much appreciated.

Sorry, I was in christmas holidays since today.

  1. You run this script on any machine that can access the mail server via IMAP and the RC server via external webhook URL (a default incoming webhook is needed).
  2. That might be possible, please take a look at the webhook logic yourself. You might need to implement a custom JS script for this.

Hi thank you for this very promising looking suggestion! I need some help implementing it though. Yes, where do I put this script? In Administration → Integrations → Incoming?

I came across your script, but unfortunately it hangs on me when integrating it.

I have created a framework at Rocket.Chat under Integration and Incoming. There I got a WebHook URL.

Did I understand correctly that I don’t need to put a script there? I need to run your script somewhere where Phyton is installed.

Mail server and access data in your script and the URL of WebHook also ? When I do this I get an error.

}
requests.post(json=mail, url=rocket_hook)

The URL must be there ?

In your script is used German, I assume that you are German?

The script relies on the presence of a secrets.py file as one can see in the last import on top of the file. That file contains all the not public variables the script needs to function, so in this case username, password and rocket_hook.

You can remove that and hardcode the values if you want. As this is tracked in our Gitlab, the secrets are in an external file to keep them out of Gitlab.

thank you for the quick reply.

but I’m just too stupid.
I create in the same folder as the scipt is a file called security.sy and write in what syntax the values pure ?

I have now tested a little more. But I can not get it to run with hardcodet.

NameError: name ‘username’ is not defined

Even if I enter my username, I get the not defined.

Please explain me how to handle this security.py.

where do i create it and in which syntax do the variables have to go in.

  1. You should not use a python script that you found on the internet, if you do not understand what it does.
  2. The file is called secrets.py and contains simple python variables named username, password and rocket_hook. If you are not able to do this, see point 1.