LoginSignup
0
0

More than 3 years have passed since last update.

discord botを利用してスマホから.emlを読めるようにする

Posted at

概要

iOSでメールアプリとしてSparkを使用しているのですが、たまに転送メールが本文に表示されず.emlファイルとして添付されていることがあります。(これはThunderbird利用者側の設定など原因で生じるそうです。-> Mozilla質問箱)
この.emlファイルはiphoneで直接開くことができません。有料アプリやオンラインの変換ページを利用すれば見ることはできますが、微妙に手間です。これをdiscord botで解決します。

今回のdiscord botのsourceはPythonで書かれています。
.emlファイルから内容を抽出する過程はこちらの内容を利用させていただきました。-> Qiita

目標の機能

  • スマホから.emlファイルをdiscord botのいるチャンネルやDMに送信すると、その内容のテキストファイルがdiscordに送信される。
  • 添付ファイルも送信される。(こちらの機能は未確認です)

メールの本文は長くなりがちなので、discordにmessageのcontentではなく、テキストファイルとして送信するようにしました。

source

importなど

MailParser以外は今回はあまり関係のない内容です。

main.py
from MailParser import MailParser

import discord
from discord.ext import commands
description = ""
bot = commands.Bot(command_prefix="?", description=description)

@bot.event
async def on_ready():
    print("Logged in as")
    print(bot.user.name)
    print(bot.user.id)
    print("------")

ファイル受信

@bot.eventon_messageの末尾にでも追加します。

main.py
@bot.event
async def on_message(message):
    # 添付ファイルがある場合に
    if (len(message.attachments) > 0):
        for att in message.attachments:
            # 拡張子が.emlかどうか判断
            file_extension = att.filename.split(".")[-1]
            if file_extension == ".eml":
                await read_eml(message.channel, await att.read())

emlの内容送信

文字化けを避けるため、Shift-JISでencodeしています。

main.py
async def read_eml(discord_channel, file_content: bytes):
    """emlファイルを読み込み, 内容を表示します"""
    # eml読み取り
    eml_result = MailParser(file_content).get_attr_data2()
    # 
    file_path = f"{os.path.dirname(__file__)}/../out/eml.txt"
    # shift-jisじゃないと文字化けする -> Chromeくんさぁ
    with open(file=file_path, mode="w", encoding="shift-jis", errors="replace") as f:
        f.write(eml_result["content"])
    await discord_channel.send(file=discord.File(file_path))
    for att in eml_result["attach"]:
        with open(f"{os.path.dirname(__file__)}/../out/{att['name']}", "wb") as f:
            f.write(att["data"])
        await discord_channel.send(file=discord.File(att["name"]))

emlの内容読み取り(MailParserを少し変更)

contentにsubjectを追加し、添付ファイルも返すmethodを追加します。

main.py
def get_attr_data2(self):
    """
    メールデータの取得
    """
    mail_content = f"""\
SUBJECT: {self.subject}

----

FROM: {self.from_address}
TO: {self.to_address}
CC: {self.cc_address}

----

{self.body}

----

ATTACH_FILE_NAME:
{",".join([ s["name"] for s in self.attach_file_list])}
"""
    return {"content":mail_content, "attach":self.attach_file_list}

setattr(MailParser, get_attr_data2.__name__, get_attr_data2)

使用方法

  1. .emlファイルを共有からDiscordに送信します。
  2. botがテキストファイルを送り返します。
  3. browserで開くと、内容が表示されます。

EML_view_ss.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0