{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# Unix Email\n\nCreate a directed graph, allowing multiple edges and self loops, from a unix\nmailbox. The nodes are email addresses with links that point from the sender\nto the receivers. The edge data is a Python email.Message object which\ncontains all of the email message data.\n\nThis example shows the power of `DiGraph` to hold edge data of arbitrary Python\nobjects (in this case a list of email messages).\n\n\nThe sample unix email mailbox called \"unix_email.mbox\" may be found here:\n\n- https://github.com/networkx/networkx/blob/main/examples/drawing/unix_email.mbox\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"from email.utils import getaddresses, parseaddr\nimport mailbox\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\n\n# unix mailbox recipe\n# see https://docs.python.org/3/library/mailbox.html\n\n\ndef mbox_graph():\n mbox = mailbox.mbox(\"unix_email.mbox\") # parse unix mailbox\n\n G = nx.MultiDiGraph() # create empty graph\n\n # parse each messages and build graph\n for msg in mbox: # msg is python email.Message.Message object\n (source_name, source_addr) = parseaddr(msg[\"From\"]) # sender\n # get all recipients\n # see https://docs.python.org/3/library/email.html\n tos = msg.get_all(\"to\", [])\n ccs = msg.get_all(\"cc\", [])\n resent_tos = msg.get_all(\"resent-to\", [])\n resent_ccs = msg.get_all(\"resent-cc\", [])\n all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)\n # now add the edges for this mail message\n for target_name, target_addr in all_recipients:\n G.add_edge(source_addr, target_addr, message=msg)\n\n return G\n\n\nG = mbox_graph()\n\n# print edges with message subject\nfor u, v, d in G.edges(data=True):\n print(f\"From: {u} To: {v} Subject: {d['message']['Subject']}\")\n\npos = nx.spring_layout(G, iterations=10, seed=227)\nnx.draw(G, pos, node_size=0, alpha=0.4, edge_color=\"r\", font_size=16, with_labels=True)\nax = plt.gca()\nax.margins(0.08)\nplt.show()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.7"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Generated by dwww version 1.16 on Wed Apr 8 10:58:34 CEST 2026.