Statistics
| Branch: | Revision:

iof-tools / networkxMiCe / networkx-master / examples / drawing / plot_unix_email.py @ 5cef0f13

History | View | Annotate | Download (2.21 KB)

1
#!/usr/bin/env python
2
"""
3
==========
4
Unix Email
5
==========
6

7
Create a directed graph, allowing multiple edges and self loops, from
8
a unix mailbox.  The nodes are email addresses with links
9
that point from the sender to the receivers.  The edge data
10
is a Python email.Message object which contains all of
11
the email message data.
12

13
This example shows the power of `DiGraph` to hold edge data
14
of arbitrary Python objects (in this case a list of email messages).
15

16
The sample unix email mailbox called "unix_email.mbox" may be found here:
17
https://raw.githubusercontent.com/networkx/networkx/master/examples/drawing/unix_email.mbox
18

19
"""
20
# Author: Aric Hagberg (hagberg@lanl.gov)
21

    
22
#    Copyright (C) 2005-2019 by
23
#    Aric Hagberg <hagberg@lanl.gov>
24
#    Dan Schult <dschult@colgate.edu>
25
#    Pieter Swart <swart@lanl.gov>
26
#    All rights reserved.
27
#    BSD license.
28

    
29
from email.utils import getaddresses, parseaddr
30
import mailbox
31
import sys
32

    
33
import matplotlib.pyplot as plt
34
import networkx as nx
35

    
36
# unix mailbox recipe
37
# see https://docs.python.org/3/library/mailbox.html
38

    
39
def mbox_graph():
40
    mbox = mailbox.mbox("unix_email.mbox")  # parse unix mailbox
41

    
42
    G = nx.MultiDiGraph()  # create empty graph
43

    
44
    # parse each messages and build graph
45
    for msg in mbox:  # msg is python email.Message.Message object
46
        (source_name, source_addr) = parseaddr(msg['From'])  # sender
47
        # get all recipients
48
        # see https://docs.python.org/3/library/email.html
49
        tos = msg.get_all('to', [])
50
        ccs = msg.get_all('cc', [])
51
        resent_tos = msg.get_all('resent-to', [])
52
        resent_ccs = msg.get_all('resent-cc', [])
53
        all_recipients = getaddresses(tos + ccs + resent_tos + resent_ccs)
54
        # now add the edges for this mail message
55
        for (target_name, target_addr) in all_recipients:
56
            G.add_edge(source_addr, target_addr, message=msg)
57

    
58
    return G
59

    
60

    
61
if __name__ == '__main__':
62

    
63
    G = mbox_graph()
64

    
65
    # print edges with message subject
66
    for (u, v, d) in G.edges(data=True):
67
        print("From: %s To: %s Subject: %s" % (u, v, d['message']["Subject"]))
68

    
69
    pos = nx.spring_layout(G, iterations=10)
70
    nx.draw(G, pos, node_size=0, alpha=0.4, edge_color='r', font_size=16, with_labels=True)
71
    plt.show()