1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
|
%global _empty_manifest_terminate_build 0
Name: python-O365
Version: 2.0.26
Release: 1
Summary: Microsoft Graph and Office 365 API made easy
License: Apache License 2.0
URL: https://github.com/O365/python-o365
Source0: https://mirrors.nju.edu.cn/pypi/web/packages/9e/34/8002946103dc0b2306a3ab27df5421353ed03188f68fc925c58db18d69bd/O365-2.0.26.tar.gz
BuildArch: noarch
Requires: python3-requests
Requires: python3-requests-oauthlib
Requires: python3-dateutil
Requires: python3-pytz
Requires: python3-tzlocal
Requires: python3-beautifulsoup4
Requires: python3-stringcase
%description
[](https://pepy.tech/project/O365)
[](https://pypi.python.org/pypi/O365)
[](https://pypi.python.org/pypi/O365/)
[](https://travis-ci.org/O365/python-o365)
# O365 - Microsoft Graph and Office 365 API made easy
> Detailed usage documentation is [still in progress](https://o365.github.io/python-o365/latest/index.html)
This project aims to make interacting with Microsoft Graph and Office 365 easy to do in a Pythonic way.
Access to Email, Calendar, Contacts, OneDrive, etc. Are easy to do in a way that feel easy and straight forward to beginners and feels just right to seasoned python programmer.
The project is currently developed and maintained by [Janscas](https://github.com/janscas).
#### Core developers
- [Janscas](https://github.com/janscas)
- [Toben Archer](https://github.com/Narcolapser)
- [Geethanadh](https://github.com/GeethanadhP)
**We are always open to new pull requests!**
#### Rebuilding HTML Docs
- Install `sphinx` python library
`pip install sphinx==2.2.2`
- Run the shell script `build_docs.sh`, or copy the command from the file when using on windows
#### Quick example on sending a message:
```python
from O365 import Account
credentials = ('client_id', 'client_secret')
account = Account(credentials)
m = account.new_message()
m.to.add('to_example@example.com')
m.subject = 'Testing!'
m.body = "George Best quote: I've stopped drinking, but only while I'm asleep."
m.send()
```
### Why choose O365?
- Almost Full Support for MsGraph and Office 365 Rest Api.
- Good Abstraction layer between each Api. Change the api (Graph vs Office365) and don't worry about the api internal implementation.
- Full oauth support with automatic handling of refresh tokens.
- Automatic handling between local datetimes and server datetimes. Work with your local datetime and let this library do the rest.
- Change between different resource with ease: access shared mailboxes, other users resources, SharePoint resources, etc.
- Pagination support through a custom iterator that handles future requests automatically. Request Infinite items!
- A query helper to help you build custom OData queries (filter, order, select and search).
- Modular ApiComponents can be created and built to achieve further functionality.
___
This project was also a learning resource for us. This is a list of not so common python idioms used in this project:
- New unpacking technics: `def method(argument, *, with_name=None, **other_params):`
- Enums: `from enum import Enum`
- Factory paradigm
- Package organization
- Timezone conversion and timezone aware datetimes
- Etc. ([see the code!](https://github.com/O365/python-o365/tree/master/O365))
What follows is kind of a wiki...
## Table of contents
- [Install](#install)
- [Usage](#usage)
- [Authentication](#authentication)
- [Protocols](#protocols)
- [Account Class and Modularity](#account)
- [MailBox](#mailbox)
- [AddressBook](#addressbook)
- [Directory and Users](#directory-and-users)
- [Calendar](#calendar)
- [Tasks](#tasks)
- [OneDrive](#onedrive)
- [Excel](#excel)
- [SharePoint](#sharepoint)
- [Planner](#planner)
- [Outlook Categories](#outlook-categories)
- [Utils](#utils)
## Install
O365 is available on pypi.org. Simply run `pip install O365` to install it.
Requirements: >= Python 3.4
Project dependencies installed by pip:
- requests
- requests-oauthlib
- beatifulsoup4
- stringcase
- python-dateutil
- tzlocal
- pytz
## Usage
The first step to be able to work with this library is to register an application and retrieve the auth token. See [Authentication](#authentication).
It is highly recommended to add the "offline_access" permission and request this scope when authenticating. Otherwise the library will only have access to the user resources for 1 hour. See [Permissions and Scopes](#permissions-and-scopes).
With the access token retrieved and stored you will be able to perform api calls to the service.
A common pattern to check for authentication and use the library is this one:
```python
scopes = ['my_required_scopes'] # you can use scope helpers here (see Permissions and Scopes section)
account = Account(credentials)
if not account.is_authenticated: # will check if there is a token and has not expired
# ask for a login
# console based authentication See Authentication for other flows
account.authenticate(scopes=scopes)
# now we are autheticated
# use the library from now on
# ...
```
## Authentication
You can only authenticate using oauth athentication as Microsoft deprecated basic auth on November 1st 2018.
There are currently three authentication methods:
- [Authenticate on behalf of a user](https://docs.microsoft.com/en-us/graph/auth-v2-user?context=graph%2Fapi%2F1.0&view=graph-rest-1.0):
Any user will give consent to the app to access it's resources.
This oauth flow is called **authorization code grant flow**. This is the default authentication method used by this library.
- [Authenticate on behalf of a user (public)](https://docs.microsoft.com/en-us/graph/auth-v2-user?context=graph%2Fapi%2F1.0&view=graph-rest-1.0):
Same as the former but for public apps where the client secret can't be secured. Client secret is not required.
- [Authenticate with your own identity](https://docs.microsoft.com/en-us/graph/auth-v2-service?context=graph%2Fapi%2F1.0&view=graph-rest-1.0):
This will use your own identity (the app identity). This oauth flow is called **client credentials grant flow**.
> 'Authenticate with your own identity' is not an allowed method for **Microsoft Personal accounts**.
When to use one or the other and requirements:
Topic | On behalf of a user *(auth_flow_type=='authorization')* | On behalf of a user (public) *(auth_flow_type=='public')* | With your own identity *(auth_flow_type=='credentials')*
:---: | :---: | :---: | :---:
**Register the App** | Required | Required | Required
**Requires Admin Consent** | Only on certain advanced permissions | Only on certain advanced permissions | Yes, for everything
**App Permission Type** | Delegated Permissions (on behalf of the user) | Delegated Permissions (on behalf of the user) | Application Permissions
**Auth requirements** | Client Id, Client Secret, Authorization Code | Client Id, Authorization Code | Client Id, Client Secret
**Authentication** | 2 step authentication with user consent | 2 step authentication with user consent | 1 step authentication
**Auth Scopes** | Required | Required | None
**Token Expiration** | 60 Minutes without refresh token or 90 days* | 60 Minutes without refresh token or 90 days* | 60 Minutes*
**Login Expiration** | Unlimited if there is a refresh token and as long as a re| Unlimited if there is a refresh token and as long as a refresh is done within the 90 days | Unlimited
**Resources** | Access the user resources, and any shared resources | Access the user resources, and any shared resources | All Azure AD users the app has access to
**Microsoft Account Type** | Any | Any | Not Allowed for Personal Accounts
**Tenant ID Required** | Defaults to "common" | Defaults to "common" | Required (can't be "common")
**O365 will automatically refresh the token for you on either authentication method. The refresh token lasts 90 days but it's refreshed on each connection so as long as you connect within 90 days you can have unlimited access.*
The `Connection` Class handles the authentication.
#### Oauth Authentication
This section is explained using Microsoft Graph Protocol, almost the same applies to the Office 365 REST API.
##### Authentication Steps
1. To allow authentication you first need to register your application at [Azure App Registrations](https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationsListBlade).
1. Login at [Azure Portal (App Registrations)](https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationsListBlade)
1. Create an app. Set a name.
1. In Supported account types choose "Accounts in any organizational directory and personal Microsoft accounts (e.g. Skype, Xbox, Outlook.com)", if you are using a personal account.
1. Set the redirect uri (Web) to: `https://login.microsoftonline.com/common/oauth2/nativeclient` and click register. This needs to be inserted into the "Redirect URI" text box as simply checking the check box next to this link seems to be insufficent. This is the default redirect uri used by this library, but you can use any other if you want.
1. Write down the Application (client) ID. You will need this value.
1. Under "Certificates & secrets", generate a new client secret. Set the expiration preferably to never. Write down the value of the client secret created now. It will be hidden later on.
1. Under Api Permissions:
- When authenticating "on behalf of a user":
1. add the **delegated permissions** for Microsoft Graph you want (see scopes).
1. It is highly recommended to add "offline_access" permission. If not the user you will have to re-authenticate every hour.
- When authenticating "with your own identity":
1. add the **application permissions** for Microsoft Graph you want.
1. Click on the Grant Admin Consent button (if you have admin permissions) or wait until the admin has given consent to your application.
As an example, to read and send emails use:
1. Mail.ReadWrite
1. Mail.Send
1. User.Read
1. Then you need to login for the first time to get the access token that will grant access to the user resources.
To authenticate (login) you can use [different authentication interfaces](#different-authentication-interfaces). On the following examples we will be using the Console Based Interface but you can use any one.
- When authenticating on behalf of a user:
> **Important:** In case you can't secure the client secret you can use the auth flow type 'public' which only requires the client id.
1. Instantiate an `Account` object with the credentials (client id and client secret).
1. Call `account.authenticate` and pass the scopes you want (the ones you previously added on the app registration portal).
> Note: when using the "on behalf of a user" authentication, you can pass the scopes to either the `Account` init or to the authenticate method. Either way is correct.
You can pass "protocol scopes" (like: "https://graph.microsoft.com/Calendars.ReadWrite") to the method or use "[scope helpers](https://github.com/O365/python-o365/blob/master/O365/connection.py#L34)" like ("message_all").
If you pass protocol scopes, then the `account` instance must be initialized with the same protocol used by the scopes. By using scope helpers you can abstract the protocol from the scopes and let this library work for you.
Finally, you can mix and match "protocol scopes" with "scope helpers".
Go to the [procotol section](#protocols) to know more about them.
For Example (following the previous permissions added):
```python
from O365 import Account
credentials = ('my_client_id', 'my_client_secret')
# the default protocol will be Microsoft Graph
# the default authentication method will be "on behalf of a user"
account = Account(credentials)
if account.authenticate(scopes=['basic', 'message_all']):
print('Authenticated!')
# 'basic' adds: 'offline_access' and 'https://graph.microsoft.com/User.Read'
# 'message_all' adds: 'https://graph.microsoft.com/Mail.ReadWrite' and 'https://graph.microsoft.com/Mail.Send'
```
When using the "on behalf of the user" authentication method, this method call will print a url that the user must visit to give consent to the app on the required permissions.
The user must then visit this url and give consent to the application. When consent is given, the page will rediret to: "https://login.microsoftonline.com/common/oauth2/nativeclient" by default (you can change this) with a url query param called 'code'.
Then the user must copy the resulting page url and paste it back on the console.
The method will then return True if the login attempt was succesful.
- When authenticating with your own identity:
1. Instantiate an `Account` object with the credentials (client id and client secret), specifying the parameter `auth_flow_type` to *"credentials"*. You also need to provide a 'tenant_id'. You don't need to specify any scopes.
1. Call `account.authenticate`. This call will request a token for you and store it in the backend. No user interaction is needed. The method will store the token in the backend and return True if the authentication succeeded.
For Example:
```python
from O365 import Account
credentials = ('my_client_id', 'my_client_secret')
# the default protocol will be Microsoft Graph
account = Account(credentials, auth_flow_type='credentials', tenant_id='my-tenant-id')
if account.authenticate():
print('Authenticated!')
```
1. At this point you will have an access token stored that will provide valid credentials when using the api.
The access token only lasts **60 minutes**, but the app try will automatically request new access tokens.
When using the "on behalf of a user" authentication method this is accomplished through the refresh tokens (if and only if you added the "offline_access" permission), but note that a refresh token only lasts for 90 days. So you must use it before or you will need to request a new access token again (no new consent needed by the user, just a login).
If your application needs to work for more than 90 days without user interaction and without interacting with the API, then you must implement a periodic call to `Connection.refresh_token` before the 90 days have passed.
**Take care: the access (and refresh) token must remain protected from unauthorized users.**
Under the "on behalf of a user" authentication method, if you change the scope requested, then the current token won't work, and you will need the user to give consent again on the application to gain access to the new scopes requested.
##### Different Authentication Interfaces
To acomplish the authentication you can basically use different approaches.
The following apply to the "on behalf of a user" authentication method as this is 2-step authentication flow.
For the "with your own identity" authentication method, you can just use `account.authenticate` as it's not going to require a console input.
1. Console based authentication interface:
You can authenticate using a console. The best way to achieve this is by using the `authenticate` method of the `Account` class.
```python
account = Account(credentials)
account.authenticate(scopes=['basic', 'message_all'])
```
The `authenticate` method will print into the console a url that you will have to visit to achieve authentication.
Then after visiting the link and authenticate you will have to paste back the resulting url into the console.
The method will return `True` and print a message if it was succesful.
**Tip:** When using MacOs the console is limited to 1024 characters. If your url has multiple scopes it can exceed this limit. To solve this. Just `import readline` a the top of your script.
1. Web app based authentication interface:
You can authenticate your users in a web environment by following this steps:
1. First ensure you are using an appropiate TokenBackend to store the auth tokens (See Token storage below).
1. From a handler redirect the user to the Microsoft login url. Provide a callback. Store the state.
1. From the callback handler complete the authentication with the state and other data.
The following example is done using Flask.
```python
@route('/stepone')
def auth_step_one():
callback = 'my absolute url to auth_step_two_callback'
account = Account(credentials)
url, state = account.con.get_authorization_url(requested_scopes=my_scopes,
redirect_uri=callback)
# the state must be saved somewhere as it will be needed later
my_db.store_state(state) # example...
return redirect(url)
@route('/steptwo')
def auth_step_two_callback():
account = Account(credentials)
# retreive the state saved in auth_step_one
my_saved_state = my_db.get_state() # example...
# rebuild the redirect_uri used in auth_step_one
callback = 'my absolute url to auth_step_two_callback'
result = account.con.request_token(request.url,
state=my_saved_state,
redirect_uri=callback)
# if result is True, then authentication was succesful
# and the auth token is stored in the token backend
if result:
return render_template('auth_complete.html')
# else ....
```
1. Other authentication interfaces:
Finally you can configure any other flow by using `connection.get_authorization_url` and `connection.request_token` as you want.
##### Permissions and Scopes:
###### Permissions
When using oauth, you create an application and allow some resources to be accessed and used by its users.
These resources are managed with permissions. These can either be delegated (on behalf of a user) or aplication permissions.
The former are used when the authentication method is "on behalf of a user". Some of these require administrator consent.
The latter when using the "with your own identity" authentication method. All of these require administrator consent.
###### Scopes
The scopes only matter when using the "on behalf of a user" authentication method.
> Note: You only need the scopes when login as those are kept stored within the token on the token backend.
The user of this library can then request access to one or more of this resources by providing scopes to the oauth provider.
> Note: If you latter on change the scopes requested, the current token will be invaled and you will have to re-authenticate. The user that logins will be asked for consent.
For example your application can have Calendar.Read, Mail.ReadWrite and Mail.Send permissions, but the application can request access only to the Mail.ReadWrite and Mail.Send permission.
This is done by providing scopes to the `Account` instance or `account.authenticate` method like so:
```python
from O365 import Account
credentials = ('client_id', 'client_secret')
scopes = ['https://graph.microsoft.com/Mail.ReadWrite', 'https://graph.microsoft.com/Mail.Send']
account = Account(credentials, scopes=scopes)
account.authenticate()
# The latter is exactly the same as passing scopes to the authenticate method like so:
# account = Account(credentials)
# account.authenticate(scopes=scopes)
```
Scope implementation depends on the protocol used. So by using protocol data you can automatically set the scopes needed.
This is implemented by using 'scope helpers'. Those are little helpers that group scope functionality and abstract the protocol used.
Scope Helper | Scopes included
:--- | :---
basic | 'offline_access' and 'User.Read'
mailbox | 'Mail.Read'
mailbox_shared | 'Mail.Read.Shared'
mailbox_settings | 'MailboxSettings.ReadWrite'
message_send | 'Mail.Send'
message_send_shared | 'Mail.Send.Shared'
message_all | 'Mail.ReadWrite' and 'Mail.Send'
message_all_shared | 'Mail.ReadWrite.Shared' and 'Mail.Send.Shared'
address_book | 'Contacts.Read'
address_book_shared | 'Contacts.Read.Shared'
address_book_all | 'Contacts.ReadWrite'
address_book_all_shared | 'Contacts.ReadWrite.Shared'
calendar | 'Calendars.Read'
calendar_shared | 'Calendars.Read.Shared'
calendar_all | 'Calendars.ReadWrite'
calendar_shared_all | 'Calendars.ReadWrite.Shared'
tasks | 'Tasks.Read'
tasks_all | 'Tasks.ReadWrite'
users | 'User.ReadBasic.All'
onedrive | 'Files.Read.All'
onedrive_all | 'Files.ReadWrite.All'
sharepoint | 'Sites.Read.All'
sharepoint_dl | 'Sites.ReadWrite.All'
You can get the same scopes as before using protocols and scope helpers like this:
```python
protocol_graph = MSGraphProtocol()
scopes_graph = protocol.get_scopes_for('message all')
# scopes here are: ['https://graph.microsoft.com/Mail.ReadWrite', 'https://graph.microsoft.com/Mail.Send']
account = Account(credentials, scopes=scopes_graph)
```
```python
protocol_office = MSOffice365Protocol()
scopes_office = protocol.get_scopes_for('message all')
# scopes here are: ['https://outlook.office.com/Mail.ReadWrite', 'https://outlook.office.com/Mail.Send']
account = Account(credentials, scopes=scopes_office)
```
> Note: When passing scopes at the `Account` initialization or on the `account.authenticate` method, the scope helpers are autommatically converted to the protocol flavor.
>Those are the only places where you can use scope helpers. Any other object using scopes (such as the `Connection` object) expects scopes that are already set for the protocol.
##### Token storage:
When authenticating you will retrieve oauth tokens. If you don't want a one time access you will have to store the token somewhere.
O365 makes no assumptions on where to store the token and tries to abstract this from the library usage point of view.
You can choose where and how to store tokens by using the proper Token Backend.
**Take care: the access (and refresh) token must remain protected from unauthorized users.**
The library will call (at different stages) the token backend methods to load and save the token.
Methods that load tokens:
- `account.is_authenticated` property will try to load the token if is not already loaded.
- `connection.get_session`: this method is called when there isn't a request session set. By default it will not try to load the token. Set `load_token=True` to load it.
Methods that stores tokens:
- `connection.request_token`: by default will store the token, but you can set `store_token=False` to avoid it.
- `connection.refresh_token`: by default will store the token. To avoid it change `connection.store_token` to False. This however it's a global setting (that only affects the `refresh_token` method). If you only want the next refresh operation to not store the token you will have to set it back to True afterwards.
To store the token you will have to provide a properly configured TokenBackend.
Actually there are only two implemented (but you can easely implement more like a CookieBackend, RedisBackend, etc.):
- `FileSystemTokenBackend` (Default backend): Stores and retrieves tokens from the file system. Tokens are stored as files.
- `FirestoreTokenBackend`: Stores and retrives tokens from a Google Firestore Datastore. Tokens are stored as documents within a collection.
For example using the FileSystem Token Backend:
```python
from O365 import Account, FileSystemTokenBackend
credentials = ('id', 'secret')
# this will store the token under: "my_project_folder/my_folder/my_token.txt".
# you can pass strings to token_path or Path instances from pathlib
token_backend = FileSystemTokenBackend(token_path='my_folder', token_filename='my_token.txt')
account = Account(credentials, token_backend=token_backend)
# This account instance tokens will be stored on the token_backend configured before.
# You don't have to do anything more
# ...
```
And now using the same example using FirestoreTokenBackend:
```python
from O365 import Account
from O365.utils import FirestoreBackend
from google.cloud import firestore
credentials = ('id', 'secret')
# this will store the token on firestore under the tokens collection on the defined doc_id.
# you can pass strings to token_path or Path instances from pathlib
user_id = 'whatever the user id is' # used to create the token document id
document_id = 'token_{}'.format(user_id) # used to uniquely store this token
token_backend = FirestoreBackend(client=firestore.Client(), collection='tokens', doc_id=document_id)
account = Account(credentials, token_backend=token_backend)
# This account instance tokens will be stored on the token_backend configured before.
# You don't have to do anything more
# ...
```
To implement a new TokenBackend:
1. Subclass `BaseTokenBackend`
1. Implement the following methods:
- `__init__` (don't forget to call `super().__init__`)
- `load_token`: this should load the token from the desired backend and return a `Token` instance or None
- `save_token`: this should store the `self.token` in the desired backend.
- Optionally you can implement: `check_token`, `delete_token` and `should_refresh_token`
The `should_refresh_token` method is intended to be implemented for environments where multiple Connection instances are running on paralel.
This method should check if it's time to refresh the token or not.
The chosen backend can store a flag somewhere to answer this question.
This can avoid race conditions between different instances trying to refresh the token at once, when only one should make the refresh.
The method should return three posible values:
- **True**: then the Connection will refresh the token.
- **False**: then the Connection will NOT refresh the token.
- **None**: then this method already executed the refresh and therefore the Connection does not have to.
By default this always returns True as it's asuming there is are no parallel connections running at once.
There are two examples of this method in the examples folder [here](https://github.com/O365/python-o365/blob/master/examples/token_backends.py).
## Protocols
Protocols handles the aspects of communications between different APIs.
This project uses either the Microsoft Graph APIs (by default) or the Office 365 APIs.
But, you can use many other Microsoft APIs as long as you implement the protocol needed.
You can use one or the other:
- `MSGraphProtocol` to use the [Microsoft Graph API](https://developer.microsoft.com/en-us/graph/docs/concepts/overview)
- `MSOffice365Protocol` to use the [Office 365 API](https://msdn.microsoft.com/en-us/office/office365/api/api-catalog)
Both protocols are similar but consider the following:
Reasons to use `MSGraphProtocol`:
- It is the recommended Protocol by Microsoft.
- It can access more resources over Office 365 (for example OneDrive)
Reasons to use `MSOffice365Protocol`:
- It can send emails with attachments up to 150 MB. MSGraph only allows 4MB on each request (UPDATE: Starting 22 October'19 you can [upload files up to 150MB with MSGraphProtocol **beta** version](https://developer.microsoft.com/en-us/office/blogs/attaching-large-files-to-outlook-messages-in-microsoft-graph-preview/))
The default protocol used by the `Account` Class is `MSGraphProtocol`.
You can implement your own protocols by inheriting from `Protocol` to communicate with other Microsoft APIs.
You can instantiate and use protocols like this:
```python
from O365 import Account, MSGraphProtocol # same as from O365.connection import MSGraphProtocol
# ...
# try the api version beta of the Microsoft Graph endpoint.
protocol = MSGraphProtocol(api_version='beta') # MSGraphProtocol defaults to v1.0 api version
account = Account(credentials, protocol=protocol)
```
##### Resources:
Each API endpoint requires a resource. This usually defines the owner of the data.
Every protocol defaults to resource 'ME'. 'ME' is the user which has given consent, but you can change this behaviour by providing a different default resource to the protocol constructor.
> Note: When using the "with your own identity" authentication method the resource 'ME' is overwritten to be blank as the authentication method already states that you are login with your own identity.
For example when accessing a shared mailbox:
```python
# ...
account = Account(credentials=my_credentials, main_resource='shared_mailbox@example.com')
# Any instance created using account will inherit the resource defined for account.
```
This can be done however at any point. For example at the protocol level:
```python
# ...
protocol = MSGraphProtocol(default_resource='shared_mailbox@example.com')
account = Account(credentials=my_credentials, protocol=protocol)
# now account is accesing the shared_mailbox@example.com in every api call.
shared_mailbox_messages = account.mailbox().get_messages()
```
Instead of defining the resource used at the account or protocol level, you can provide it per use case as follows:
```python
# ...
account = Account(credentials=my_credentials) # account defaults to 'ME' resource
mailbox = account.mailbox('shared_mailbox@example.com') # mailbox is using 'shared_mailbox@example.com' resource instead of 'ME'
# or:
message = Message(parent=account, main_resource='shared_mailbox@example.com') # message is using 'shared_mailbox@example.com' resource
```
Usually you will work with the default 'ME' resource, but you can also use one of the following:
- **'me'**: the user which has given consent. the default for every protocol. Overwritten when using "with your own identity" authentication method (Only available on the authorization auth_flow_type).
- **'user:user@domain.com'**: a shared mailbox or a user account for which you have permissions. If you don't provide 'user:' will be infered anyways.
- **'site:sharepoint-site-id'**: a sharepoint site id.
- **'group:group-site-id'**: a office365 group id.
By setting the resource prefix (such as **'user:'** or **'group:'**) you help the library understand the type of resource. You can also pass it like 'users/example@exampl.com'. Same applies to the other resource prefixes.
## Account Class and Modularity <a name="account"></a>
Usually you will only need to work with the `Account` Class. This is a wrapper around all functionality.
But you can also work only with the pieces you want.
For example, instead of:
```python
from O365 import Account
account = Account(('client_id', 'client_secret'))
message = account.new_message()
# ...
mailbox = account.mailbox()
# ...
```
You can work only with the required pieces:
```python
from O365 import Connection, MSGraphProtocol
from O365.message import Message
from O365.mailbox import MailBox
protocol = MSGraphProtocol()
scopes = ['...']
con = Connection(('client_id', 'client_secret'), scopes=scopes)
message = Message(con=con, protocol=protocol)
# ...
mailbox = MailBox(con=con, protocol=protocol)
message2 = Message(parent=mailbox) # message will inherit the connection and protocol from mailbox when using parent.
# ...
```
It's also easy to implement a custom Class.
Just Inherit from `ApiComponent`, define the endpoints, and use the connection to make requests. If needed also inherit from Protocol to handle different comunications aspects with the API server.
```python
from O365.utils import ApiComponent
class CustomClass(ApiComponent):
_endpoints = {'my_url_key': '/customendpoint'}
def __init__(self, *, parent=None, con=None, **kwargs):
# connection is only needed if you want to communicate with the api provider
self.con = parent.con if parent else con
protocol = parent.protocol if parent else kwargs.get('protocol')
main_resource = parent.main_resource
super().__init__(protocol=protocol, main_resource=main_resource)
# ...
def do_some_stuff(self):
# self.build_url just merges the protocol service_url with the enpoint passed as a parameter
# to change the service_url implement your own protocol inherinting from Protocol Class
url = self.build_url(self._endpoints.get('my_url_key'))
my_params = {'param1': 'param1'}
response = self.con.get(url, params=my_params) # note the use of the connection here.
# handle response and return to the user...
# the use it as follows:
from O365 import Connection, MSGraphProtocol
protocol = MSGraphProtocol() # or maybe a user defined protocol
con = Connection(('client_id', 'client_secret'), scopes=protocol.get_scopes_for(['...']))
custom_class = CustomClass(con=con, protocol=protocol)
custom_class.do_some_stuff()
```
## MailBox
Mailbox groups the funcionality of both the messages and the email folders.
These are the scopes needed to work with the `MailBox` and `Message` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*Mail.Read* | *mailbox* | To only read my mailbox
*Mail.Read.Shared* | *mailbox_shared* | To only read another user / shared mailboxes
*Mail.Send* | *message_send, message_all* | To only send message
*Mail.Send.Shared* | *message_send_shared, message_all_shared* | To only send message as another user / shared mailbox
*Mail.ReadWrite* | *message_all* | To read and save messages in my mailbox
*MailboxSettings.ReadWrite* | *mailbox_settings* | To read and write suer mailbox settings
```python
mailbox = account.mailbox()
inbox = mailbox.inbox_folder()
for message in inbox.get_messages():
print(message)
sent_folder = mailbox.sent_folder()
for message in sent_folder.get_messages():
print(message)
m = mailbox.new_message()
m.to.add('to_example@example.com')
m.body = 'George Best quote: In 1969 I gave up women and alcohol - it was the worst 20 minutes of my life.'
m.save_draft()
```
#### Email Folder
Represents a `Folder` within your email mailbox.
You can get any folder in your mailbox by requesting child folders or filtering by name.
```python
mailbox = account.mailbox()
archive = mailbox.get_folder(folder_name='archive') # get a folder with 'archive' name
child_folders = archive.get_folders(25) # get at most 25 child folders of 'archive' folder
for folder in child_folders:
print(folder.name, folder.parent_id)
new_folder = archive.create_child_folder('George Best Quotes')
```
#### Message
An email object with all its data and methods.
Creating a draft message is as easy as this:
```python
message = mailbox.new_message()
message.to.add(['example1@example.com', 'example2@example.com'])
message.sender.address = 'my_shared_account@example.com' # changing the from address
message.body = 'George Best quote: I might go to Alcoholics Anonymous, but I think it would be difficult for me to remain anonymous'
message.attachments.add('george_best_quotes.txt')
message.save_draft() # save the message on the cloud as a draft in the drafts folder
```
Working with saved emails is also easy:
```python
query = mailbox.new_query().on_attribute('subject').contains('george best') # see Query object in Utils
messages = mailbox.get_messages(limit=25, query=query)
message = messages[0] # get the first one
message.mark_as_read()
reply_msg = message.reply()
if 'example@example.com' in reply_msg.to: # magic methods implemented
reply_msg.body = 'George Best quote: I spent a lot of money on booze, birds and fast cars. The rest I just squandered.'
else:
reply_msg.body = 'George Best quote: I used to go missing a lot... Miss Canada, Miss United Kingdom, Miss World.'
reply_msg.send()
```
##### Sending Inline Images
You can send inline images by doing this:
```python
# ...
msg = account.new_message()
msg.to.add('george@best.com')
msg.attachments.add('my_image.png')
att = msg.attachments[0] # get the attachment object
# this is super important for this to work.
att.is_inline = True
att.content_id = 'image.png'
# notice we insert an image tag with source to: "cid:{content_id}"
body = """
<html>
<body>
<strong>There should be an image here:</strong>
<p>
<img src="cid:image.png">
</p>
</body>
</html>
"""
msg.body = body
msg.send()
```
##### Retrieving Message Headers
You can retrieve message headers by doing this:
```python
# ...
mb = account.mailbox()
msg = mb.get_message(query=mb.q().select('internet_message_headers'))
print(msg.message_headers) # returns a list of dicts.
```
Note that only message headers and other properties added to the select statement will be present.
##### Saving as EML
Messages and attached messages can be saved as *.eml.
- Save message as "eml":
```python
msg.save_as_eml(to_path=Path('my_saved_email.eml'))
```
- Save attached message as "eml":
Carefull: there's no way to identify that an attachment is in fact a message. You can only check if the attachment.attachment_type == 'item'.
if is of type "item" then it can be a message (or an event, etc...). You will have to determine this yourself.
```python
msg_attachment = msg.attachments[0] # the first attachment is attachment.attachment_type == 'item' and I know it's a message.
msg.attachments.save_as_eml(msg_attachment, to_path=Path('my_saved_email.eml'))
```
#### Mailbox Settings
The mailbox settings and associated methods.
Retrieve and update mailbox auto reply settings:
```python
from O365.mailbox import AutoReplyStatus, ExternalAudience
mailboxsettings = mailbox.get_settings()
ars = mailboxsettings.automaticrepliessettings
ars.scheduled_startdatetime = start # Sets the start date/time
ars.scheduled_enddatetime = end # Sets the end date/time
ars.status = AutoReplyStatus.SCHEDULED # DISABLED/SCHEDULED/ALWAYSENABLED - Uses start/end date/time if scheduled.
ars.external_audience = ExternalAudience.NONE # NONE/CONTACTSONLY/ALL
ars.internal_reply_message = "ARS Internal" # Internal message
ars.external_reply_message = "ARS External" # External message
mailboxsettings.save()
```
Alternatively to enable and disable
```python
mailboxsettings.save()
mailbox.set_automatic_reply(
"Internal",
"External",
scheduled_start_date_time=start, # Status will be 'scheduled' if start/end supplied, otherwise 'alwaysEnabled'
scheduled_end_date_time=end,
externalAudience=ExternalAudience.NONE, # Defaults to ALL
)
mailbox.set_disable_reply()
```
## AddressBook
AddressBook groups the functionality of both the Contact Folders and Contacts. Outlook Distribution Groups are not supported (By the Microsoft API's).
These are the scopes needed to work with the `AddressBook` and `Contact` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*Contacts.Read* | *address_book* | To only read my personal contacts
*Contacts.Read.Shared* | *address_book_shared* | To only read another user / shared mailbox contacts
*Contacts.ReadWrite* | *address_book_all* | To read and save personal contacts
*Contacts.ReadWrite.Shared* | *address_book_all_shared* | To read and save contacts from another user / shared mailbox
*User.ReadBasic.All* | *users* | To only read basic properties from users of my organization (User.Read.All requires administrator consent).
#### Contact Folders
Represents a Folder within your Contacts Section in Office 365.
AddressBook class represents the parent folder (it's a folder itself).
You can get any folder in your address book by requesting child folders or filtering by name.
```python
address_book = account.address_book()
contacts = address_book.get_contacts(limit=None) # get all the contacts in the Personal Contacts root folder
work_contacts_folder = address_book.get_folder(folder_name='Work Contacts') # get a folder with 'Work Contacts' name
message_to_all_contats_in_folder = work_contacts_folder.new_message() # creates a draft message with all the contacts as recipients
message_to_all_contats_in_folder.subject = 'Hallo!'
message_to_all_contats_in_folder.body = """
George Best quote:
If you'd given me the choice of going out and beating four men and smashing a goal in
from thirty yards against Liverpool or going to bed with Miss World,
it would have been a difficult choice. Luckily, I had both.
"""
message_to_all_contats_in_folder.send()
# querying folders is easy:
child_folders = address_book.get_folders(25) # get at most 25 child folders
for folder in child_folders:
print(folder.name, folder.parent_id)
# creating a contact folder:
address_book.create_child_folder('new folder')
```
#### The Global Address List
Office 365 API (Nor MS Graph API) has no concept such as the Outlook Global Address List.
However you can use the [Users API](https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/users) to access all the users within your organization.
Without admin consent you can only access a few properties of each user such as name and email and litte more.
You can search by name or retrieve a contact specifying the complete email.
- Basic Permision needed is Users.ReadBasic.All (limit info)
- Full Permision is Users.Read.All but needs admin consent.
To search the Global Address List (Users API):
```python
global_address_list = account.directory()
# for backwards compatibilty only this also works and returns a Directory object:
# global_address_list = account.address_book(address_book='gal')
# start a new query:
q = global_address_list.new_query('display_name')
q.startswith('George Best')
for user in global_address_list.get_users(query=q):
print(user)
```
To retrieve a contact by their email:
```python
contact = global_address_list.get_user('example@example.com')
```
#### Contacts
Everything returned from an `AddressBook` instance is a `Contact` instance.
Contacts have all the information stored as attributes
Creating a contact from an `AddressBook`:
```python
new_contact = address_book.new_contact()
new_contact.name = 'George Best'
new_contact.job_title = 'football player'
new_contact.emails.add('george@best.com')
new_contact.save() # saved on the cloud
message = new_contact.new_message() # Bonus: send a message to this contact
# ...
new_contact.delete() # Bonus: deteled from the cloud
```
## Directory and Users
The Directory object can retrieve users.
A User instance contains by default the [basic properties of the user](https://docs.microsoft.com/en-us/graph/api/user-list?view=graph-rest-1.0&tabs=http#optional-query-parameters).
If you want to include more, you will have to select the desired properties manually.
Check [The Global Address List](#the-global-address-list) for further information.
```python
directory = account.directory()
for user in directory.get_users():
print(user)
```
## Calendar
The calendar and events functionality is group in a `Schedule` object.
A `Schedule` instance can list and create calendars. It can also list or create events on the default user calendar.
To use other calendars use a `Calendar` instance.
These are the scopes needed to work with the `Schedule`, `Calendar` and `Event` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*Calendars.Read* | *calendar* | To only read my personal calendars
*Calendars.Read.Shared* | *calendar_shared* | To only read another user / shared mailbox calendars
*Calendars.ReadWrite* | *calendar_all* | To read and save personal calendars
*Calendars.ReadWrite.Shared* | *calendar_shared_all* | To read and save calendars from another user / shared mailbox
Working with the `Schedule` instance:
```python
import datetime as dt
# ...
schedule = account.schedule()
calendar = schedule.get_default_calendar()
new_event = calendar.new_event() # creates a new unsaved event
new_event.subject = 'Recruit George Best!'
new_event.location = 'England'
# naive datetimes will automatically be converted to timezone aware datetime
# objects using the local timezone detected or the protocol provided timezone
new_event.start = dt.datetime(2019, 9, 5, 19, 45)
# so new_event.start becomes: datetime.datetime(2018, 9, 5, 19, 45, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>)
new_event.recurrence.set_daily(1, end=dt.datetime(2019, 9, 10))
new_event.remind_before_minutes = 45
new_event.save()
```
Working with `Calendar` instances:
```python
calendar = schedule.get_calendar(calendar_name='Birthdays')
calendar.name = 'Football players birthdays'
calendar.update()
q = calendar.new_query('start').greater_equal(dt.datetime(2018, 5, 20))
q.chain('and').on_attribute('end').less_equal(dt.datetime(2018, 5, 24))
birthdays = calendar.get_events(query=q, include_recurring=True) # include_recurring=True will include repeated events on the result set.
for event in birthdays:
if event.subject == 'George Best Birthday':
# He died in 2005... but we celebrate anyway!
event.accept("I'll attend!") # send a response accepting
else:
event.decline("No way I'm comming, I'll be in Spain", send_response=False) # decline the event but don't send a reponse to the organizer
```
#### Notes regarding Calendars and Events:
1. Include_recurring=True:
> It's important to know that when querying events with `include_recurring=True` (which is the default), it is required that you must provide a query parameter with the start and end attributes defined.
> Unlike when using `include_recurring=False` those attributes will NOT filter the data based on the operations you set on the query (greater_equal, less, etc.) but just filter the events start datetime between the provided start and end datetimes.
1. Shared Calendars:
There are some known issues when working with [shared calendars](https://docs.microsoft.com/en-us/graph/known-issues#calendars) in Microsoft Graph.
1. Event attachments:
For some unknow reason, microsoft does not allow to upload an attachment at the event creation time (as opposed with message attachments).
See [this](https://stackoverflow.com/questions/46438302/office365-rest-api-creating-a-calendar-event-with-attachments?rq=1).
So, to upload attachments to Events, first save the event, then attach the message and save again.
## Tasks
The tasks functionality is grouped in a `ToDo` object.
A `ToDo` instance can list and create task folders. It can also list or create tasks on the default user folder. To use other folders use a `Folder` instance.
These are the scopes needed to work with the `ToDo`, `Folder` and `Task` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*Tasks.Read* | *tasks* | To only read my personal tasks
*Tasks.ReadWrite* | *tasks_all* | To read and save personal calendars
Working with the `ToDo` instance:
```python
import datetime as dt
# ...
todo = account.tasks()
#list current tasks
folder = todo.get_default_folder()
new_task = folder.new_task() # creates a new unsaved task
new_task.subject = 'Send contract to George Best'
new_task.due = dt.datetime(2020, 9, 25, 18, 30)
new_task.save()
#some time later....
new_task.mark_completed()
new_task.save()
# naive datetimes will automatically be converted to timezone aware datetime
# objects using the local timezone detected or the protocol provided timezone
# as with the Calendar functionality
```
Working with `Folder` instances:
```python
#create a new folder
new_folder = todo.new_folder('Defenders')
#rename a folder
folder = todo.get_folder(folder_name='Strikers')
folder.name = 'Forwards'
folder.update()
#list current tasks
task_list = folder.get_tasks()
for task in task_list:
print(task)
print('')
```
## OneDrive
The `Storage` class handles all functionality around One Drive and Document Library Storage in SharePoint.
The `Storage` instance allows to retrieve `Drive` instances which handles all the Files and Folders from within the selected `Storage`.
Usually you will only need to work with the default drive. But the `Storage` instances can handle multiple drives.
A `Drive` will allow you to work with Folders and Files.
These are the scopes needed to work with the `Storage`, `Drive` and `DriveItem` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*Files.Read* | | To only read my files
*Files.Read.All* | *onedrive* | To only read all the files the user has access
*Files.ReadWrite* | | To read and save my files
*Files.ReadWrite.All* | *onedrive_all* | To read and save all the files the user has access
```python
account = Account(credentials=my_credentials)
storage = account.storage() # here we get the storage instance that handles all the storage options.
# list all the drives:
drives = storage.get_drives()
# get the default drive
my_drive = storage.get_default_drive() # or get_drive('drive-id')
# get some folders:
root_folder = my_drive.get_root_folder()
attachments_folder = my_drive.get_special_folder('attachments')
# iterate over the first 25 items on the root folder
for item in root_folder.get_items(limit=25):
if item.is_folder:
print(list(item.get_items(2))) # print the first to element on this folder.
elif item.is_file:
if item.is_photo:
print(item.camera_model) # print some metadata of this photo
elif item.is_image:
print(item.dimensions) # print the image dimensions
else:
# regular file:
print(item.mime_type) # print the mime type
```
Both Files and Folders are DriveItems. Both Image and Photo are Files, but Photo is also an Image. All have some different methods and properties.
Take care when using 'is_xxxx'.
When copying a DriveItem the api can return a direct copy of the item or a pointer to a resource that will inform on the progress of the copy operation.
```python
# copy a file to the documents special folder
documents_folder = my_drive.get_special_folder('documents')
files = my_drive.search('george best quotes', limit=1)
if files:
george_best_quotes = files[0]
operation = george_best_quotes.copy(target=documents_folder) # operation here is an instance of CopyOperation
# to check for the result just loop over check_status.
# check_status is a generator that will yield a new status and progress until the file is finally copied
for status, progress in operation.check_status(): # if it's an async operations, this will request to the api for the status in every loop
print('{} - {}'.format(status, progress)) # prints 'in progress - 77.3' until finally completed: 'completed - 100.0'
copied_item = operation.get_item() # the copy operation is completed so you can get the item.
if copied_item:
copied_item.delete() # ... oops!
```
You can also work with share permissions:
```python
current_permisions = file.get_permissions() # get all the current permissions on this drive_item (some may be inherited)
# share with link
permission = file.share_with_link(share_type='edit')
if permission:
print(permission.share_link) # the link you can use to share this drive item
# share with invite
permission = file.share_with_invite(recipients='george_best@best.com', send_email=True, message='Greetings!!', share_type='edit')
if permission:
print(permission.granted_to) # the person you share this item with
```
You can also:
```python
# download files:
file.download(to_path='/quotes/')
# upload files:
# if the uploaded file is bigger than 4MB the file will be uploaded in chunks of 5 MB until completed.
# this can take several requests and can be time consuming.
uploaded_file = folder.upload_file(item='path_to_my_local_file')
# restore versions:
versions = file.get_versions()
for version in versions:
if version.name == '2.0':
version.restore() # restore the version 2.0 of this file
# ... and much more ...
```
## Excel
You can interact with new excel files (.xlsx) stored in OneDrive or a SharePoint Document Library.
You can retrieve workbooks, worksheets, tables, and even cell data.
You can also write to any excel online.
To work with excel files, first you have to retrieve a `File` instance using the OneDrive or SharePoint functionallity.
The scopes needed to work with the `WorkBook` and Excel related classes are the same used by OneDrive.
This is how you update a cell value:
```python
from O365.excel import WorkBook
# given a File instance that is a xlsx file ...
excel_file = WorkBook(my_file_instance) # my_file_instance should be an instance of File.
ws = excel_file.get_worksheet('my_worksheet')
cella1 = ws.get_range('A1')
cella1.values = 35
cella1.update()
```
#### Workbook Sessions
When interacting with excel, you can use a workbook session to efficiently make changes in a persistent or nonpersistent way.
This sessions become usefull if you perform numerous changes to the excel file.
The default is to use a session in a persistent way.
Sessions expire after some time of inactivity. When working with persistent sessions, new sessions will automatically be created when old ones expire.
You can however change this when creating the `Workbook` instance:
```python
excel_file = WorkBook(my_file_instance, use_session=False, persist=False)
```
#### Available Objects
After creating the `WorkBook` instance you will have access to the following objects:
- WorkSheet
- Range and NamedRange
- Table, TableColumn and TableRow
- RangeFormat (to format ranges)
- Charts (not available for now)
Some examples:
Set format for a given range
```python
# ...
my_range = ws.get_range('B2:C10')
fmt = myrange.get_format()
fmt.font.bold = True
fmt.update()
```
Autofit Columns:
```python
ws.get_range('B2:C10').get_format().auto_fit_columns()
```
Get values from Table:
```python
table = ws.get_table('my_table')
column = table.get_column_at_index(1)
values = column.values[0] # values returns a two dimensional array.
```
## SharePoint
The SharePoint api is done but there are no docs yet. Look at the sharepoint.py file to get insights.
These are the scopes needed to work with the `SharePoint` and `Site` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*Sites.Read.All* | *sharepoint* | To only read sites, lists and items
*Sites.ReadWrite.All* | *sharepoint_dl* | To read and save sites, lists and items
## Planner
The planner api is done but there are no docs yet. Look at the planner.py file to get insights.
The planner functionality requires Administrator Permission.
## Outlook Categories
You can retrive, update, create and delete outlook categories.
These categories can be used to categorize Messages, Events and Contacts.
These are the scopes needed to work with the `SharePoint` and `Site` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*MailboxSettings.Read* | *-* | To only read outlook settingss
*MailboxSettings.ReadWrite* | *settings_all* | To read and write outlook settings
Example:
```python
from O365.category import CategoryColor
oc = account.outlook_categories()
categories = oc.get_categories()
for category in categories:
print(category.name, category.color)
my_category = oc.create_category('Important Category', color=CategoryColor.RED)
my_category.update_color(CategoryColor.DARKGREEN)
my_category.delete() # oops!
```
## Utils
#### Pagination
When using certain methods, it is possible that you request more items than the api can return in a single api call.
In this case the Api, returns a "next link" url where you can pull more data.
When this is the case, the methods in this library will return a `Pagination` object which abstracts all this into a single iterator.
The pagination object will request "next links" as soon as they are needed.
For example:
```python
mailbox = account.mailbox()
messages = mailbox.get_messages(limit=1500) # the Office 365 and MS Graph API have a 999 items limit returned per api call.
# Here messages is a Pagination instance. It's an Iterator so you can iterate over.
# The first 999 iterations will be normal list iterations, returning one item at a time.
# When the iterator reaches the 1000 item, the Pagination instance will call the api again requesting exactly 500 items
# or the items specified in the batch parameter (see later).
for message in messages:
print(message.subject)
```
When using certain methods you will have the option to specify not only a limit option (the number of items to be returned) but a batch option.
This option will indicate the method to request data to the api in batches until the limit is reached or the data consumed.
This is usefull when you want to optimize memory or network latency.
For example:
```python
messages = mailbox.get_messages(limit=100, batch=25)
# messages here is a Pagination instance
# when iterating over it will call the api 4 times (each requesting 25 items).
for message in messages: # 100 loops with 4 requests to the api server
print(message.subject)
```
#### The Query helper
When using the Office 365 API you can filter, order, select, expand or search on some fields.
This filtering is tedious as is using [Open Data Protocol (OData)](http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part2-url-conventions/odata-v4.0-errata03-os-part2-url-conventions-complete.html).
Every `ApiComponent` (such as `MailBox`) implements a new_query method that will return a `Query` instance.
This `Query` instance can handle the filtering, sorting, selecting, expanding and search very easily.
For example:
```python
query = mailbox.new_query() # you can use the shorthand: mailbox.q()
query = query.on_attribute('subject').contains('george best').chain('or').startswith('quotes')
# 'created_date_time' will automatically be converted to the protocol casing.
# For example when using MS Graph this will become 'createdDateTime'.
query = query.chain('and').on_attribute('created_date_time').greater(datetime(2018, 3, 21))
print(query)
# contains(subject, 'george best') or startswith(subject, 'quotes') and createdDateTime gt '2018-03-21T00:00:00Z'
# note you can pass naive datetimes and those will be converted to you local timezone and then send to the api as UTC in iso8601 format
# To use Query objetcs just pass it to the query parameter:
filtered_messages = mailbox.get_messages(query=query)
```
You can also specify specific data to be retrieved with "select":
```python
# select only some properties for the retrieved messages:
query = mailbox.new_query().select('subject', 'to_recipients', 'created_date_time')
messages_with_selected_properties = mailbox.get_messages(query=query)
```
You can also search content. As said in the graph docs:
> You can currently search only message and person collections. A $search request returns up to 250 results. You cannot use $filter or $orderby in a search request.
> If you do a search on messages and specify only a value without specific message properties, the search is carried out on the default search properties of from, subject, and body.
```python
# searching is the easy part ;)
query = mailbox.q().search('george best is da boss')
messages = mailbox.get_messages(query=query)
```
#### Request Error Handling
Whenever a Request error raises, the connection object will raise an exception.
Then the exception will be captured and logged it to the stdout with it's message, an return Falsy (None, False, [], etc...)
HttpErrors 4xx (Bad Request) and 5xx (Internal Server Error) are considered exceptions and raised also by the connection.
You can tell the `Connection` to not raise http errors by passing `raise_http_errors=False` (defaults to True).
%package -n python3-O365
Summary: Microsoft Graph and Office 365 API made easy
Provides: python-O365
BuildRequires: python3-devel
BuildRequires: python3-setuptools
BuildRequires: python3-pip
%description -n python3-O365
[](https://pepy.tech/project/O365)
[](https://pypi.python.org/pypi/O365)
[](https://pypi.python.org/pypi/O365/)
[](https://travis-ci.org/O365/python-o365)
# O365 - Microsoft Graph and Office 365 API made easy
> Detailed usage documentation is [still in progress](https://o365.github.io/python-o365/latest/index.html)
This project aims to make interacting with Microsoft Graph and Office 365 easy to do in a Pythonic way.
Access to Email, Calendar, Contacts, OneDrive, etc. Are easy to do in a way that feel easy and straight forward to beginners and feels just right to seasoned python programmer.
The project is currently developed and maintained by [Janscas](https://github.com/janscas).
#### Core developers
- [Janscas](https://github.com/janscas)
- [Toben Archer](https://github.com/Narcolapser)
- [Geethanadh](https://github.com/GeethanadhP)
**We are always open to new pull requests!**
#### Rebuilding HTML Docs
- Install `sphinx` python library
`pip install sphinx==2.2.2`
- Run the shell script `build_docs.sh`, or copy the command from the file when using on windows
#### Quick example on sending a message:
```python
from O365 import Account
credentials = ('client_id', 'client_secret')
account = Account(credentials)
m = account.new_message()
m.to.add('to_example@example.com')
m.subject = 'Testing!'
m.body = "George Best quote: I've stopped drinking, but only while I'm asleep."
m.send()
```
### Why choose O365?
- Almost Full Support for MsGraph and Office 365 Rest Api.
- Good Abstraction layer between each Api. Change the api (Graph vs Office365) and don't worry about the api internal implementation.
- Full oauth support with automatic handling of refresh tokens.
- Automatic handling between local datetimes and server datetimes. Work with your local datetime and let this library do the rest.
- Change between different resource with ease: access shared mailboxes, other users resources, SharePoint resources, etc.
- Pagination support through a custom iterator that handles future requests automatically. Request Infinite items!
- A query helper to help you build custom OData queries (filter, order, select and search).
- Modular ApiComponents can be created and built to achieve further functionality.
___
This project was also a learning resource for us. This is a list of not so common python idioms used in this project:
- New unpacking technics: `def method(argument, *, with_name=None, **other_params):`
- Enums: `from enum import Enum`
- Factory paradigm
- Package organization
- Timezone conversion and timezone aware datetimes
- Etc. ([see the code!](https://github.com/O365/python-o365/tree/master/O365))
What follows is kind of a wiki...
## Table of contents
- [Install](#install)
- [Usage](#usage)
- [Authentication](#authentication)
- [Protocols](#protocols)
- [Account Class and Modularity](#account)
- [MailBox](#mailbox)
- [AddressBook](#addressbook)
- [Directory and Users](#directory-and-users)
- [Calendar](#calendar)
- [Tasks](#tasks)
- [OneDrive](#onedrive)
- [Excel](#excel)
- [SharePoint](#sharepoint)
- [Planner](#planner)
- [Outlook Categories](#outlook-categories)
- [Utils](#utils)
## Install
O365 is available on pypi.org. Simply run `pip install O365` to install it.
Requirements: >= Python 3.4
Project dependencies installed by pip:
- requests
- requests-oauthlib
- beatifulsoup4
- stringcase
- python-dateutil
- tzlocal
- pytz
## Usage
The first step to be able to work with this library is to register an application and retrieve the auth token. See [Authentication](#authentication).
It is highly recommended to add the "offline_access" permission and request this scope when authenticating. Otherwise the library will only have access to the user resources for 1 hour. See [Permissions and Scopes](#permissions-and-scopes).
With the access token retrieved and stored you will be able to perform api calls to the service.
A common pattern to check for authentication and use the library is this one:
```python
scopes = ['my_required_scopes'] # you can use scope helpers here (see Permissions and Scopes section)
account = Account(credentials)
if not account.is_authenticated: # will check if there is a token and has not expired
# ask for a login
# console based authentication See Authentication for other flows
account.authenticate(scopes=scopes)
# now we are autheticated
# use the library from now on
# ...
```
## Authentication
You can only authenticate using oauth athentication as Microsoft deprecated basic auth on November 1st 2018.
There are currently three authentication methods:
- [Authenticate on behalf of a user](https://docs.microsoft.com/en-us/graph/auth-v2-user?context=graph%2Fapi%2F1.0&view=graph-rest-1.0):
Any user will give consent to the app to access it's resources.
This oauth flow is called **authorization code grant flow**. This is the default authentication method used by this library.
- [Authenticate on behalf of a user (public)](https://docs.microsoft.com/en-us/graph/auth-v2-user?context=graph%2Fapi%2F1.0&view=graph-rest-1.0):
Same as the former but for public apps where the client secret can't be secured. Client secret is not required.
- [Authenticate with your own identity](https://docs.microsoft.com/en-us/graph/auth-v2-service?context=graph%2Fapi%2F1.0&view=graph-rest-1.0):
This will use your own identity (the app identity). This oauth flow is called **client credentials grant flow**.
> 'Authenticate with your own identity' is not an allowed method for **Microsoft Personal accounts**.
When to use one or the other and requirements:
Topic | On behalf of a user *(auth_flow_type=='authorization')* | On behalf of a user (public) *(auth_flow_type=='public')* | With your own identity *(auth_flow_type=='credentials')*
:---: | :---: | :---: | :---:
**Register the App** | Required | Required | Required
**Requires Admin Consent** | Only on certain advanced permissions | Only on certain advanced permissions | Yes, for everything
**App Permission Type** | Delegated Permissions (on behalf of the user) | Delegated Permissions (on behalf of the user) | Application Permissions
**Auth requirements** | Client Id, Client Secret, Authorization Code | Client Id, Authorization Code | Client Id, Client Secret
**Authentication** | 2 step authentication with user consent | 2 step authentication with user consent | 1 step authentication
**Auth Scopes** | Required | Required | None
**Token Expiration** | 60 Minutes without refresh token or 90 days* | 60 Minutes without refresh token or 90 days* | 60 Minutes*
**Login Expiration** | Unlimited if there is a refresh token and as long as a re| Unlimited if there is a refresh token and as long as a refresh is done within the 90 days | Unlimited
**Resources** | Access the user resources, and any shared resources | Access the user resources, and any shared resources | All Azure AD users the app has access to
**Microsoft Account Type** | Any | Any | Not Allowed for Personal Accounts
**Tenant ID Required** | Defaults to "common" | Defaults to "common" | Required (can't be "common")
**O365 will automatically refresh the token for you on either authentication method. The refresh token lasts 90 days but it's refreshed on each connection so as long as you connect within 90 days you can have unlimited access.*
The `Connection` Class handles the authentication.
#### Oauth Authentication
This section is explained using Microsoft Graph Protocol, almost the same applies to the Office 365 REST API.
##### Authentication Steps
1. To allow authentication you first need to register your application at [Azure App Registrations](https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationsListBlade).
1. Login at [Azure Portal (App Registrations)](https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationsListBlade)
1. Create an app. Set a name.
1. In Supported account types choose "Accounts in any organizational directory and personal Microsoft accounts (e.g. Skype, Xbox, Outlook.com)", if you are using a personal account.
1. Set the redirect uri (Web) to: `https://login.microsoftonline.com/common/oauth2/nativeclient` and click register. This needs to be inserted into the "Redirect URI" text box as simply checking the check box next to this link seems to be insufficent. This is the default redirect uri used by this library, but you can use any other if you want.
1. Write down the Application (client) ID. You will need this value.
1. Under "Certificates & secrets", generate a new client secret. Set the expiration preferably to never. Write down the value of the client secret created now. It will be hidden later on.
1. Under Api Permissions:
- When authenticating "on behalf of a user":
1. add the **delegated permissions** for Microsoft Graph you want (see scopes).
1. It is highly recommended to add "offline_access" permission. If not the user you will have to re-authenticate every hour.
- When authenticating "with your own identity":
1. add the **application permissions** for Microsoft Graph you want.
1. Click on the Grant Admin Consent button (if you have admin permissions) or wait until the admin has given consent to your application.
As an example, to read and send emails use:
1. Mail.ReadWrite
1. Mail.Send
1. User.Read
1. Then you need to login for the first time to get the access token that will grant access to the user resources.
To authenticate (login) you can use [different authentication interfaces](#different-authentication-interfaces). On the following examples we will be using the Console Based Interface but you can use any one.
- When authenticating on behalf of a user:
> **Important:** In case you can't secure the client secret you can use the auth flow type 'public' which only requires the client id.
1. Instantiate an `Account` object with the credentials (client id and client secret).
1. Call `account.authenticate` and pass the scopes you want (the ones you previously added on the app registration portal).
> Note: when using the "on behalf of a user" authentication, you can pass the scopes to either the `Account` init or to the authenticate method. Either way is correct.
You can pass "protocol scopes" (like: "https://graph.microsoft.com/Calendars.ReadWrite") to the method or use "[scope helpers](https://github.com/O365/python-o365/blob/master/O365/connection.py#L34)" like ("message_all").
If you pass protocol scopes, then the `account` instance must be initialized with the same protocol used by the scopes. By using scope helpers you can abstract the protocol from the scopes and let this library work for you.
Finally, you can mix and match "protocol scopes" with "scope helpers".
Go to the [procotol section](#protocols) to know more about them.
For Example (following the previous permissions added):
```python
from O365 import Account
credentials = ('my_client_id', 'my_client_secret')
# the default protocol will be Microsoft Graph
# the default authentication method will be "on behalf of a user"
account = Account(credentials)
if account.authenticate(scopes=['basic', 'message_all']):
print('Authenticated!')
# 'basic' adds: 'offline_access' and 'https://graph.microsoft.com/User.Read'
# 'message_all' adds: 'https://graph.microsoft.com/Mail.ReadWrite' and 'https://graph.microsoft.com/Mail.Send'
```
When using the "on behalf of the user" authentication method, this method call will print a url that the user must visit to give consent to the app on the required permissions.
The user must then visit this url and give consent to the application. When consent is given, the page will rediret to: "https://login.microsoftonline.com/common/oauth2/nativeclient" by default (you can change this) with a url query param called 'code'.
Then the user must copy the resulting page url and paste it back on the console.
The method will then return True if the login attempt was succesful.
- When authenticating with your own identity:
1. Instantiate an `Account` object with the credentials (client id and client secret), specifying the parameter `auth_flow_type` to *"credentials"*. You also need to provide a 'tenant_id'. You don't need to specify any scopes.
1. Call `account.authenticate`. This call will request a token for you and store it in the backend. No user interaction is needed. The method will store the token in the backend and return True if the authentication succeeded.
For Example:
```python
from O365 import Account
credentials = ('my_client_id', 'my_client_secret')
# the default protocol will be Microsoft Graph
account = Account(credentials, auth_flow_type='credentials', tenant_id='my-tenant-id')
if account.authenticate():
print('Authenticated!')
```
1. At this point you will have an access token stored that will provide valid credentials when using the api.
The access token only lasts **60 minutes**, but the app try will automatically request new access tokens.
When using the "on behalf of a user" authentication method this is accomplished through the refresh tokens (if and only if you added the "offline_access" permission), but note that a refresh token only lasts for 90 days. So you must use it before or you will need to request a new access token again (no new consent needed by the user, just a login).
If your application needs to work for more than 90 days without user interaction and without interacting with the API, then you must implement a periodic call to `Connection.refresh_token` before the 90 days have passed.
**Take care: the access (and refresh) token must remain protected from unauthorized users.**
Under the "on behalf of a user" authentication method, if you change the scope requested, then the current token won't work, and you will need the user to give consent again on the application to gain access to the new scopes requested.
##### Different Authentication Interfaces
To acomplish the authentication you can basically use different approaches.
The following apply to the "on behalf of a user" authentication method as this is 2-step authentication flow.
For the "with your own identity" authentication method, you can just use `account.authenticate` as it's not going to require a console input.
1. Console based authentication interface:
You can authenticate using a console. The best way to achieve this is by using the `authenticate` method of the `Account` class.
```python
account = Account(credentials)
account.authenticate(scopes=['basic', 'message_all'])
```
The `authenticate` method will print into the console a url that you will have to visit to achieve authentication.
Then after visiting the link and authenticate you will have to paste back the resulting url into the console.
The method will return `True` and print a message if it was succesful.
**Tip:** When using MacOs the console is limited to 1024 characters. If your url has multiple scopes it can exceed this limit. To solve this. Just `import readline` a the top of your script.
1. Web app based authentication interface:
You can authenticate your users in a web environment by following this steps:
1. First ensure you are using an appropiate TokenBackend to store the auth tokens (See Token storage below).
1. From a handler redirect the user to the Microsoft login url. Provide a callback. Store the state.
1. From the callback handler complete the authentication with the state and other data.
The following example is done using Flask.
```python
@route('/stepone')
def auth_step_one():
callback = 'my absolute url to auth_step_two_callback'
account = Account(credentials)
url, state = account.con.get_authorization_url(requested_scopes=my_scopes,
redirect_uri=callback)
# the state must be saved somewhere as it will be needed later
my_db.store_state(state) # example...
return redirect(url)
@route('/steptwo')
def auth_step_two_callback():
account = Account(credentials)
# retreive the state saved in auth_step_one
my_saved_state = my_db.get_state() # example...
# rebuild the redirect_uri used in auth_step_one
callback = 'my absolute url to auth_step_two_callback'
result = account.con.request_token(request.url,
state=my_saved_state,
redirect_uri=callback)
# if result is True, then authentication was succesful
# and the auth token is stored in the token backend
if result:
return render_template('auth_complete.html')
# else ....
```
1. Other authentication interfaces:
Finally you can configure any other flow by using `connection.get_authorization_url` and `connection.request_token` as you want.
##### Permissions and Scopes:
###### Permissions
When using oauth, you create an application and allow some resources to be accessed and used by its users.
These resources are managed with permissions. These can either be delegated (on behalf of a user) or aplication permissions.
The former are used when the authentication method is "on behalf of a user". Some of these require administrator consent.
The latter when using the "with your own identity" authentication method. All of these require administrator consent.
###### Scopes
The scopes only matter when using the "on behalf of a user" authentication method.
> Note: You only need the scopes when login as those are kept stored within the token on the token backend.
The user of this library can then request access to one or more of this resources by providing scopes to the oauth provider.
> Note: If you latter on change the scopes requested, the current token will be invaled and you will have to re-authenticate. The user that logins will be asked for consent.
For example your application can have Calendar.Read, Mail.ReadWrite and Mail.Send permissions, but the application can request access only to the Mail.ReadWrite and Mail.Send permission.
This is done by providing scopes to the `Account` instance or `account.authenticate` method like so:
```python
from O365 import Account
credentials = ('client_id', 'client_secret')
scopes = ['https://graph.microsoft.com/Mail.ReadWrite', 'https://graph.microsoft.com/Mail.Send']
account = Account(credentials, scopes=scopes)
account.authenticate()
# The latter is exactly the same as passing scopes to the authenticate method like so:
# account = Account(credentials)
# account.authenticate(scopes=scopes)
```
Scope implementation depends on the protocol used. So by using protocol data you can automatically set the scopes needed.
This is implemented by using 'scope helpers'. Those are little helpers that group scope functionality and abstract the protocol used.
Scope Helper | Scopes included
:--- | :---
basic | 'offline_access' and 'User.Read'
mailbox | 'Mail.Read'
mailbox_shared | 'Mail.Read.Shared'
mailbox_settings | 'MailboxSettings.ReadWrite'
message_send | 'Mail.Send'
message_send_shared | 'Mail.Send.Shared'
message_all | 'Mail.ReadWrite' and 'Mail.Send'
message_all_shared | 'Mail.ReadWrite.Shared' and 'Mail.Send.Shared'
address_book | 'Contacts.Read'
address_book_shared | 'Contacts.Read.Shared'
address_book_all | 'Contacts.ReadWrite'
address_book_all_shared | 'Contacts.ReadWrite.Shared'
calendar | 'Calendars.Read'
calendar_shared | 'Calendars.Read.Shared'
calendar_all | 'Calendars.ReadWrite'
calendar_shared_all | 'Calendars.ReadWrite.Shared'
tasks | 'Tasks.Read'
tasks_all | 'Tasks.ReadWrite'
users | 'User.ReadBasic.All'
onedrive | 'Files.Read.All'
onedrive_all | 'Files.ReadWrite.All'
sharepoint | 'Sites.Read.All'
sharepoint_dl | 'Sites.ReadWrite.All'
You can get the same scopes as before using protocols and scope helpers like this:
```python
protocol_graph = MSGraphProtocol()
scopes_graph = protocol.get_scopes_for('message all')
# scopes here are: ['https://graph.microsoft.com/Mail.ReadWrite', 'https://graph.microsoft.com/Mail.Send']
account = Account(credentials, scopes=scopes_graph)
```
```python
protocol_office = MSOffice365Protocol()
scopes_office = protocol.get_scopes_for('message all')
# scopes here are: ['https://outlook.office.com/Mail.ReadWrite', 'https://outlook.office.com/Mail.Send']
account = Account(credentials, scopes=scopes_office)
```
> Note: When passing scopes at the `Account` initialization or on the `account.authenticate` method, the scope helpers are autommatically converted to the protocol flavor.
>Those are the only places where you can use scope helpers. Any other object using scopes (such as the `Connection` object) expects scopes that are already set for the protocol.
##### Token storage:
When authenticating you will retrieve oauth tokens. If you don't want a one time access you will have to store the token somewhere.
O365 makes no assumptions on where to store the token and tries to abstract this from the library usage point of view.
You can choose where and how to store tokens by using the proper Token Backend.
**Take care: the access (and refresh) token must remain protected from unauthorized users.**
The library will call (at different stages) the token backend methods to load and save the token.
Methods that load tokens:
- `account.is_authenticated` property will try to load the token if is not already loaded.
- `connection.get_session`: this method is called when there isn't a request session set. By default it will not try to load the token. Set `load_token=True` to load it.
Methods that stores tokens:
- `connection.request_token`: by default will store the token, but you can set `store_token=False` to avoid it.
- `connection.refresh_token`: by default will store the token. To avoid it change `connection.store_token` to False. This however it's a global setting (that only affects the `refresh_token` method). If you only want the next refresh operation to not store the token you will have to set it back to True afterwards.
To store the token you will have to provide a properly configured TokenBackend.
Actually there are only two implemented (but you can easely implement more like a CookieBackend, RedisBackend, etc.):
- `FileSystemTokenBackend` (Default backend): Stores and retrieves tokens from the file system. Tokens are stored as files.
- `FirestoreTokenBackend`: Stores and retrives tokens from a Google Firestore Datastore. Tokens are stored as documents within a collection.
For example using the FileSystem Token Backend:
```python
from O365 import Account, FileSystemTokenBackend
credentials = ('id', 'secret')
# this will store the token under: "my_project_folder/my_folder/my_token.txt".
# you can pass strings to token_path or Path instances from pathlib
token_backend = FileSystemTokenBackend(token_path='my_folder', token_filename='my_token.txt')
account = Account(credentials, token_backend=token_backend)
# This account instance tokens will be stored on the token_backend configured before.
# You don't have to do anything more
# ...
```
And now using the same example using FirestoreTokenBackend:
```python
from O365 import Account
from O365.utils import FirestoreBackend
from google.cloud import firestore
credentials = ('id', 'secret')
# this will store the token on firestore under the tokens collection on the defined doc_id.
# you can pass strings to token_path or Path instances from pathlib
user_id = 'whatever the user id is' # used to create the token document id
document_id = 'token_{}'.format(user_id) # used to uniquely store this token
token_backend = FirestoreBackend(client=firestore.Client(), collection='tokens', doc_id=document_id)
account = Account(credentials, token_backend=token_backend)
# This account instance tokens will be stored on the token_backend configured before.
# You don't have to do anything more
# ...
```
To implement a new TokenBackend:
1. Subclass `BaseTokenBackend`
1. Implement the following methods:
- `__init__` (don't forget to call `super().__init__`)
- `load_token`: this should load the token from the desired backend and return a `Token` instance or None
- `save_token`: this should store the `self.token` in the desired backend.
- Optionally you can implement: `check_token`, `delete_token` and `should_refresh_token`
The `should_refresh_token` method is intended to be implemented for environments where multiple Connection instances are running on paralel.
This method should check if it's time to refresh the token or not.
The chosen backend can store a flag somewhere to answer this question.
This can avoid race conditions between different instances trying to refresh the token at once, when only one should make the refresh.
The method should return three posible values:
- **True**: then the Connection will refresh the token.
- **False**: then the Connection will NOT refresh the token.
- **None**: then this method already executed the refresh and therefore the Connection does not have to.
By default this always returns True as it's asuming there is are no parallel connections running at once.
There are two examples of this method in the examples folder [here](https://github.com/O365/python-o365/blob/master/examples/token_backends.py).
## Protocols
Protocols handles the aspects of communications between different APIs.
This project uses either the Microsoft Graph APIs (by default) or the Office 365 APIs.
But, you can use many other Microsoft APIs as long as you implement the protocol needed.
You can use one or the other:
- `MSGraphProtocol` to use the [Microsoft Graph API](https://developer.microsoft.com/en-us/graph/docs/concepts/overview)
- `MSOffice365Protocol` to use the [Office 365 API](https://msdn.microsoft.com/en-us/office/office365/api/api-catalog)
Both protocols are similar but consider the following:
Reasons to use `MSGraphProtocol`:
- It is the recommended Protocol by Microsoft.
- It can access more resources over Office 365 (for example OneDrive)
Reasons to use `MSOffice365Protocol`:
- It can send emails with attachments up to 150 MB. MSGraph only allows 4MB on each request (UPDATE: Starting 22 October'19 you can [upload files up to 150MB with MSGraphProtocol **beta** version](https://developer.microsoft.com/en-us/office/blogs/attaching-large-files-to-outlook-messages-in-microsoft-graph-preview/))
The default protocol used by the `Account` Class is `MSGraphProtocol`.
You can implement your own protocols by inheriting from `Protocol` to communicate with other Microsoft APIs.
You can instantiate and use protocols like this:
```python
from O365 import Account, MSGraphProtocol # same as from O365.connection import MSGraphProtocol
# ...
# try the api version beta of the Microsoft Graph endpoint.
protocol = MSGraphProtocol(api_version='beta') # MSGraphProtocol defaults to v1.0 api version
account = Account(credentials, protocol=protocol)
```
##### Resources:
Each API endpoint requires a resource. This usually defines the owner of the data.
Every protocol defaults to resource 'ME'. 'ME' is the user which has given consent, but you can change this behaviour by providing a different default resource to the protocol constructor.
> Note: When using the "with your own identity" authentication method the resource 'ME' is overwritten to be blank as the authentication method already states that you are login with your own identity.
For example when accessing a shared mailbox:
```python
# ...
account = Account(credentials=my_credentials, main_resource='shared_mailbox@example.com')
# Any instance created using account will inherit the resource defined for account.
```
This can be done however at any point. For example at the protocol level:
```python
# ...
protocol = MSGraphProtocol(default_resource='shared_mailbox@example.com')
account = Account(credentials=my_credentials, protocol=protocol)
# now account is accesing the shared_mailbox@example.com in every api call.
shared_mailbox_messages = account.mailbox().get_messages()
```
Instead of defining the resource used at the account or protocol level, you can provide it per use case as follows:
```python
# ...
account = Account(credentials=my_credentials) # account defaults to 'ME' resource
mailbox = account.mailbox('shared_mailbox@example.com') # mailbox is using 'shared_mailbox@example.com' resource instead of 'ME'
# or:
message = Message(parent=account, main_resource='shared_mailbox@example.com') # message is using 'shared_mailbox@example.com' resource
```
Usually you will work with the default 'ME' resource, but you can also use one of the following:
- **'me'**: the user which has given consent. the default for every protocol. Overwritten when using "with your own identity" authentication method (Only available on the authorization auth_flow_type).
- **'user:user@domain.com'**: a shared mailbox or a user account for which you have permissions. If you don't provide 'user:' will be infered anyways.
- **'site:sharepoint-site-id'**: a sharepoint site id.
- **'group:group-site-id'**: a office365 group id.
By setting the resource prefix (such as **'user:'** or **'group:'**) you help the library understand the type of resource. You can also pass it like 'users/example@exampl.com'. Same applies to the other resource prefixes.
## Account Class and Modularity <a name="account"></a>
Usually you will only need to work with the `Account` Class. This is a wrapper around all functionality.
But you can also work only with the pieces you want.
For example, instead of:
```python
from O365 import Account
account = Account(('client_id', 'client_secret'))
message = account.new_message()
# ...
mailbox = account.mailbox()
# ...
```
You can work only with the required pieces:
```python
from O365 import Connection, MSGraphProtocol
from O365.message import Message
from O365.mailbox import MailBox
protocol = MSGraphProtocol()
scopes = ['...']
con = Connection(('client_id', 'client_secret'), scopes=scopes)
message = Message(con=con, protocol=protocol)
# ...
mailbox = MailBox(con=con, protocol=protocol)
message2 = Message(parent=mailbox) # message will inherit the connection and protocol from mailbox when using parent.
# ...
```
It's also easy to implement a custom Class.
Just Inherit from `ApiComponent`, define the endpoints, and use the connection to make requests. If needed also inherit from Protocol to handle different comunications aspects with the API server.
```python
from O365.utils import ApiComponent
class CustomClass(ApiComponent):
_endpoints = {'my_url_key': '/customendpoint'}
def __init__(self, *, parent=None, con=None, **kwargs):
# connection is only needed if you want to communicate with the api provider
self.con = parent.con if parent else con
protocol = parent.protocol if parent else kwargs.get('protocol')
main_resource = parent.main_resource
super().__init__(protocol=protocol, main_resource=main_resource)
# ...
def do_some_stuff(self):
# self.build_url just merges the protocol service_url with the enpoint passed as a parameter
# to change the service_url implement your own protocol inherinting from Protocol Class
url = self.build_url(self._endpoints.get('my_url_key'))
my_params = {'param1': 'param1'}
response = self.con.get(url, params=my_params) # note the use of the connection here.
# handle response and return to the user...
# the use it as follows:
from O365 import Connection, MSGraphProtocol
protocol = MSGraphProtocol() # or maybe a user defined protocol
con = Connection(('client_id', 'client_secret'), scopes=protocol.get_scopes_for(['...']))
custom_class = CustomClass(con=con, protocol=protocol)
custom_class.do_some_stuff()
```
## MailBox
Mailbox groups the funcionality of both the messages and the email folders.
These are the scopes needed to work with the `MailBox` and `Message` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*Mail.Read* | *mailbox* | To only read my mailbox
*Mail.Read.Shared* | *mailbox_shared* | To only read another user / shared mailboxes
*Mail.Send* | *message_send, message_all* | To only send message
*Mail.Send.Shared* | *message_send_shared, message_all_shared* | To only send message as another user / shared mailbox
*Mail.ReadWrite* | *message_all* | To read and save messages in my mailbox
*MailboxSettings.ReadWrite* | *mailbox_settings* | To read and write suer mailbox settings
```python
mailbox = account.mailbox()
inbox = mailbox.inbox_folder()
for message in inbox.get_messages():
print(message)
sent_folder = mailbox.sent_folder()
for message in sent_folder.get_messages():
print(message)
m = mailbox.new_message()
m.to.add('to_example@example.com')
m.body = 'George Best quote: In 1969 I gave up women and alcohol - it was the worst 20 minutes of my life.'
m.save_draft()
```
#### Email Folder
Represents a `Folder` within your email mailbox.
You can get any folder in your mailbox by requesting child folders or filtering by name.
```python
mailbox = account.mailbox()
archive = mailbox.get_folder(folder_name='archive') # get a folder with 'archive' name
child_folders = archive.get_folders(25) # get at most 25 child folders of 'archive' folder
for folder in child_folders:
print(folder.name, folder.parent_id)
new_folder = archive.create_child_folder('George Best Quotes')
```
#### Message
An email object with all its data and methods.
Creating a draft message is as easy as this:
```python
message = mailbox.new_message()
message.to.add(['example1@example.com', 'example2@example.com'])
message.sender.address = 'my_shared_account@example.com' # changing the from address
message.body = 'George Best quote: I might go to Alcoholics Anonymous, but I think it would be difficult for me to remain anonymous'
message.attachments.add('george_best_quotes.txt')
message.save_draft() # save the message on the cloud as a draft in the drafts folder
```
Working with saved emails is also easy:
```python
query = mailbox.new_query().on_attribute('subject').contains('george best') # see Query object in Utils
messages = mailbox.get_messages(limit=25, query=query)
message = messages[0] # get the first one
message.mark_as_read()
reply_msg = message.reply()
if 'example@example.com' in reply_msg.to: # magic methods implemented
reply_msg.body = 'George Best quote: I spent a lot of money on booze, birds and fast cars. The rest I just squandered.'
else:
reply_msg.body = 'George Best quote: I used to go missing a lot... Miss Canada, Miss United Kingdom, Miss World.'
reply_msg.send()
```
##### Sending Inline Images
You can send inline images by doing this:
```python
# ...
msg = account.new_message()
msg.to.add('george@best.com')
msg.attachments.add('my_image.png')
att = msg.attachments[0] # get the attachment object
# this is super important for this to work.
att.is_inline = True
att.content_id = 'image.png'
# notice we insert an image tag with source to: "cid:{content_id}"
body = """
<html>
<body>
<strong>There should be an image here:</strong>
<p>
<img src="cid:image.png">
</p>
</body>
</html>
"""
msg.body = body
msg.send()
```
##### Retrieving Message Headers
You can retrieve message headers by doing this:
```python
# ...
mb = account.mailbox()
msg = mb.get_message(query=mb.q().select('internet_message_headers'))
print(msg.message_headers) # returns a list of dicts.
```
Note that only message headers and other properties added to the select statement will be present.
##### Saving as EML
Messages and attached messages can be saved as *.eml.
- Save message as "eml":
```python
msg.save_as_eml(to_path=Path('my_saved_email.eml'))
```
- Save attached message as "eml":
Carefull: there's no way to identify that an attachment is in fact a message. You can only check if the attachment.attachment_type == 'item'.
if is of type "item" then it can be a message (or an event, etc...). You will have to determine this yourself.
```python
msg_attachment = msg.attachments[0] # the first attachment is attachment.attachment_type == 'item' and I know it's a message.
msg.attachments.save_as_eml(msg_attachment, to_path=Path('my_saved_email.eml'))
```
#### Mailbox Settings
The mailbox settings and associated methods.
Retrieve and update mailbox auto reply settings:
```python
from O365.mailbox import AutoReplyStatus, ExternalAudience
mailboxsettings = mailbox.get_settings()
ars = mailboxsettings.automaticrepliessettings
ars.scheduled_startdatetime = start # Sets the start date/time
ars.scheduled_enddatetime = end # Sets the end date/time
ars.status = AutoReplyStatus.SCHEDULED # DISABLED/SCHEDULED/ALWAYSENABLED - Uses start/end date/time if scheduled.
ars.external_audience = ExternalAudience.NONE # NONE/CONTACTSONLY/ALL
ars.internal_reply_message = "ARS Internal" # Internal message
ars.external_reply_message = "ARS External" # External message
mailboxsettings.save()
```
Alternatively to enable and disable
```python
mailboxsettings.save()
mailbox.set_automatic_reply(
"Internal",
"External",
scheduled_start_date_time=start, # Status will be 'scheduled' if start/end supplied, otherwise 'alwaysEnabled'
scheduled_end_date_time=end,
externalAudience=ExternalAudience.NONE, # Defaults to ALL
)
mailbox.set_disable_reply()
```
## AddressBook
AddressBook groups the functionality of both the Contact Folders and Contacts. Outlook Distribution Groups are not supported (By the Microsoft API's).
These are the scopes needed to work with the `AddressBook` and `Contact` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*Contacts.Read* | *address_book* | To only read my personal contacts
*Contacts.Read.Shared* | *address_book_shared* | To only read another user / shared mailbox contacts
*Contacts.ReadWrite* | *address_book_all* | To read and save personal contacts
*Contacts.ReadWrite.Shared* | *address_book_all_shared* | To read and save contacts from another user / shared mailbox
*User.ReadBasic.All* | *users* | To only read basic properties from users of my organization (User.Read.All requires administrator consent).
#### Contact Folders
Represents a Folder within your Contacts Section in Office 365.
AddressBook class represents the parent folder (it's a folder itself).
You can get any folder in your address book by requesting child folders or filtering by name.
```python
address_book = account.address_book()
contacts = address_book.get_contacts(limit=None) # get all the contacts in the Personal Contacts root folder
work_contacts_folder = address_book.get_folder(folder_name='Work Contacts') # get a folder with 'Work Contacts' name
message_to_all_contats_in_folder = work_contacts_folder.new_message() # creates a draft message with all the contacts as recipients
message_to_all_contats_in_folder.subject = 'Hallo!'
message_to_all_contats_in_folder.body = """
George Best quote:
If you'd given me the choice of going out and beating four men and smashing a goal in
from thirty yards against Liverpool or going to bed with Miss World,
it would have been a difficult choice. Luckily, I had both.
"""
message_to_all_contats_in_folder.send()
# querying folders is easy:
child_folders = address_book.get_folders(25) # get at most 25 child folders
for folder in child_folders:
print(folder.name, folder.parent_id)
# creating a contact folder:
address_book.create_child_folder('new folder')
```
#### The Global Address List
Office 365 API (Nor MS Graph API) has no concept such as the Outlook Global Address List.
However you can use the [Users API](https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/users) to access all the users within your organization.
Without admin consent you can only access a few properties of each user such as name and email and litte more.
You can search by name or retrieve a contact specifying the complete email.
- Basic Permision needed is Users.ReadBasic.All (limit info)
- Full Permision is Users.Read.All but needs admin consent.
To search the Global Address List (Users API):
```python
global_address_list = account.directory()
# for backwards compatibilty only this also works and returns a Directory object:
# global_address_list = account.address_book(address_book='gal')
# start a new query:
q = global_address_list.new_query('display_name')
q.startswith('George Best')
for user in global_address_list.get_users(query=q):
print(user)
```
To retrieve a contact by their email:
```python
contact = global_address_list.get_user('example@example.com')
```
#### Contacts
Everything returned from an `AddressBook` instance is a `Contact` instance.
Contacts have all the information stored as attributes
Creating a contact from an `AddressBook`:
```python
new_contact = address_book.new_contact()
new_contact.name = 'George Best'
new_contact.job_title = 'football player'
new_contact.emails.add('george@best.com')
new_contact.save() # saved on the cloud
message = new_contact.new_message() # Bonus: send a message to this contact
# ...
new_contact.delete() # Bonus: deteled from the cloud
```
## Directory and Users
The Directory object can retrieve users.
A User instance contains by default the [basic properties of the user](https://docs.microsoft.com/en-us/graph/api/user-list?view=graph-rest-1.0&tabs=http#optional-query-parameters).
If you want to include more, you will have to select the desired properties manually.
Check [The Global Address List](#the-global-address-list) for further information.
```python
directory = account.directory()
for user in directory.get_users():
print(user)
```
## Calendar
The calendar and events functionality is group in a `Schedule` object.
A `Schedule` instance can list and create calendars. It can also list or create events on the default user calendar.
To use other calendars use a `Calendar` instance.
These are the scopes needed to work with the `Schedule`, `Calendar` and `Event` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*Calendars.Read* | *calendar* | To only read my personal calendars
*Calendars.Read.Shared* | *calendar_shared* | To only read another user / shared mailbox calendars
*Calendars.ReadWrite* | *calendar_all* | To read and save personal calendars
*Calendars.ReadWrite.Shared* | *calendar_shared_all* | To read and save calendars from another user / shared mailbox
Working with the `Schedule` instance:
```python
import datetime as dt
# ...
schedule = account.schedule()
calendar = schedule.get_default_calendar()
new_event = calendar.new_event() # creates a new unsaved event
new_event.subject = 'Recruit George Best!'
new_event.location = 'England'
# naive datetimes will automatically be converted to timezone aware datetime
# objects using the local timezone detected or the protocol provided timezone
new_event.start = dt.datetime(2019, 9, 5, 19, 45)
# so new_event.start becomes: datetime.datetime(2018, 9, 5, 19, 45, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>)
new_event.recurrence.set_daily(1, end=dt.datetime(2019, 9, 10))
new_event.remind_before_minutes = 45
new_event.save()
```
Working with `Calendar` instances:
```python
calendar = schedule.get_calendar(calendar_name='Birthdays')
calendar.name = 'Football players birthdays'
calendar.update()
q = calendar.new_query('start').greater_equal(dt.datetime(2018, 5, 20))
q.chain('and').on_attribute('end').less_equal(dt.datetime(2018, 5, 24))
birthdays = calendar.get_events(query=q, include_recurring=True) # include_recurring=True will include repeated events on the result set.
for event in birthdays:
if event.subject == 'George Best Birthday':
# He died in 2005... but we celebrate anyway!
event.accept("I'll attend!") # send a response accepting
else:
event.decline("No way I'm comming, I'll be in Spain", send_response=False) # decline the event but don't send a reponse to the organizer
```
#### Notes regarding Calendars and Events:
1. Include_recurring=True:
> It's important to know that when querying events with `include_recurring=True` (which is the default), it is required that you must provide a query parameter with the start and end attributes defined.
> Unlike when using `include_recurring=False` those attributes will NOT filter the data based on the operations you set on the query (greater_equal, less, etc.) but just filter the events start datetime between the provided start and end datetimes.
1. Shared Calendars:
There are some known issues when working with [shared calendars](https://docs.microsoft.com/en-us/graph/known-issues#calendars) in Microsoft Graph.
1. Event attachments:
For some unknow reason, microsoft does not allow to upload an attachment at the event creation time (as opposed with message attachments).
See [this](https://stackoverflow.com/questions/46438302/office365-rest-api-creating-a-calendar-event-with-attachments?rq=1).
So, to upload attachments to Events, first save the event, then attach the message and save again.
## Tasks
The tasks functionality is grouped in a `ToDo` object.
A `ToDo` instance can list and create task folders. It can also list or create tasks on the default user folder. To use other folders use a `Folder` instance.
These are the scopes needed to work with the `ToDo`, `Folder` and `Task` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*Tasks.Read* | *tasks* | To only read my personal tasks
*Tasks.ReadWrite* | *tasks_all* | To read and save personal calendars
Working with the `ToDo` instance:
```python
import datetime as dt
# ...
todo = account.tasks()
#list current tasks
folder = todo.get_default_folder()
new_task = folder.new_task() # creates a new unsaved task
new_task.subject = 'Send contract to George Best'
new_task.due = dt.datetime(2020, 9, 25, 18, 30)
new_task.save()
#some time later....
new_task.mark_completed()
new_task.save()
# naive datetimes will automatically be converted to timezone aware datetime
# objects using the local timezone detected or the protocol provided timezone
# as with the Calendar functionality
```
Working with `Folder` instances:
```python
#create a new folder
new_folder = todo.new_folder('Defenders')
#rename a folder
folder = todo.get_folder(folder_name='Strikers')
folder.name = 'Forwards'
folder.update()
#list current tasks
task_list = folder.get_tasks()
for task in task_list:
print(task)
print('')
```
## OneDrive
The `Storage` class handles all functionality around One Drive and Document Library Storage in SharePoint.
The `Storage` instance allows to retrieve `Drive` instances which handles all the Files and Folders from within the selected `Storage`.
Usually you will only need to work with the default drive. But the `Storage` instances can handle multiple drives.
A `Drive` will allow you to work with Folders and Files.
These are the scopes needed to work with the `Storage`, `Drive` and `DriveItem` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*Files.Read* | | To only read my files
*Files.Read.All* | *onedrive* | To only read all the files the user has access
*Files.ReadWrite* | | To read and save my files
*Files.ReadWrite.All* | *onedrive_all* | To read and save all the files the user has access
```python
account = Account(credentials=my_credentials)
storage = account.storage() # here we get the storage instance that handles all the storage options.
# list all the drives:
drives = storage.get_drives()
# get the default drive
my_drive = storage.get_default_drive() # or get_drive('drive-id')
# get some folders:
root_folder = my_drive.get_root_folder()
attachments_folder = my_drive.get_special_folder('attachments')
# iterate over the first 25 items on the root folder
for item in root_folder.get_items(limit=25):
if item.is_folder:
print(list(item.get_items(2))) # print the first to element on this folder.
elif item.is_file:
if item.is_photo:
print(item.camera_model) # print some metadata of this photo
elif item.is_image:
print(item.dimensions) # print the image dimensions
else:
# regular file:
print(item.mime_type) # print the mime type
```
Both Files and Folders are DriveItems. Both Image and Photo are Files, but Photo is also an Image. All have some different methods and properties.
Take care when using 'is_xxxx'.
When copying a DriveItem the api can return a direct copy of the item or a pointer to a resource that will inform on the progress of the copy operation.
```python
# copy a file to the documents special folder
documents_folder = my_drive.get_special_folder('documents')
files = my_drive.search('george best quotes', limit=1)
if files:
george_best_quotes = files[0]
operation = george_best_quotes.copy(target=documents_folder) # operation here is an instance of CopyOperation
# to check for the result just loop over check_status.
# check_status is a generator that will yield a new status and progress until the file is finally copied
for status, progress in operation.check_status(): # if it's an async operations, this will request to the api for the status in every loop
print('{} - {}'.format(status, progress)) # prints 'in progress - 77.3' until finally completed: 'completed - 100.0'
copied_item = operation.get_item() # the copy operation is completed so you can get the item.
if copied_item:
copied_item.delete() # ... oops!
```
You can also work with share permissions:
```python
current_permisions = file.get_permissions() # get all the current permissions on this drive_item (some may be inherited)
# share with link
permission = file.share_with_link(share_type='edit')
if permission:
print(permission.share_link) # the link you can use to share this drive item
# share with invite
permission = file.share_with_invite(recipients='george_best@best.com', send_email=True, message='Greetings!!', share_type='edit')
if permission:
print(permission.granted_to) # the person you share this item with
```
You can also:
```python
# download files:
file.download(to_path='/quotes/')
# upload files:
# if the uploaded file is bigger than 4MB the file will be uploaded in chunks of 5 MB until completed.
# this can take several requests and can be time consuming.
uploaded_file = folder.upload_file(item='path_to_my_local_file')
# restore versions:
versions = file.get_versions()
for version in versions:
if version.name == '2.0':
version.restore() # restore the version 2.0 of this file
# ... and much more ...
```
## Excel
You can interact with new excel files (.xlsx) stored in OneDrive or a SharePoint Document Library.
You can retrieve workbooks, worksheets, tables, and even cell data.
You can also write to any excel online.
To work with excel files, first you have to retrieve a `File` instance using the OneDrive or SharePoint functionallity.
The scopes needed to work with the `WorkBook` and Excel related classes are the same used by OneDrive.
This is how you update a cell value:
```python
from O365.excel import WorkBook
# given a File instance that is a xlsx file ...
excel_file = WorkBook(my_file_instance) # my_file_instance should be an instance of File.
ws = excel_file.get_worksheet('my_worksheet')
cella1 = ws.get_range('A1')
cella1.values = 35
cella1.update()
```
#### Workbook Sessions
When interacting with excel, you can use a workbook session to efficiently make changes in a persistent or nonpersistent way.
This sessions become usefull if you perform numerous changes to the excel file.
The default is to use a session in a persistent way.
Sessions expire after some time of inactivity. When working with persistent sessions, new sessions will automatically be created when old ones expire.
You can however change this when creating the `Workbook` instance:
```python
excel_file = WorkBook(my_file_instance, use_session=False, persist=False)
```
#### Available Objects
After creating the `WorkBook` instance you will have access to the following objects:
- WorkSheet
- Range and NamedRange
- Table, TableColumn and TableRow
- RangeFormat (to format ranges)
- Charts (not available for now)
Some examples:
Set format for a given range
```python
# ...
my_range = ws.get_range('B2:C10')
fmt = myrange.get_format()
fmt.font.bold = True
fmt.update()
```
Autofit Columns:
```python
ws.get_range('B2:C10').get_format().auto_fit_columns()
```
Get values from Table:
```python
table = ws.get_table('my_table')
column = table.get_column_at_index(1)
values = column.values[0] # values returns a two dimensional array.
```
## SharePoint
The SharePoint api is done but there are no docs yet. Look at the sharepoint.py file to get insights.
These are the scopes needed to work with the `SharePoint` and `Site` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*Sites.Read.All* | *sharepoint* | To only read sites, lists and items
*Sites.ReadWrite.All* | *sharepoint_dl* | To read and save sites, lists and items
## Planner
The planner api is done but there are no docs yet. Look at the planner.py file to get insights.
The planner functionality requires Administrator Permission.
## Outlook Categories
You can retrive, update, create and delete outlook categories.
These categories can be used to categorize Messages, Events and Contacts.
These are the scopes needed to work with the `SharePoint` and `Site` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*MailboxSettings.Read* | *-* | To only read outlook settingss
*MailboxSettings.ReadWrite* | *settings_all* | To read and write outlook settings
Example:
```python
from O365.category import CategoryColor
oc = account.outlook_categories()
categories = oc.get_categories()
for category in categories:
print(category.name, category.color)
my_category = oc.create_category('Important Category', color=CategoryColor.RED)
my_category.update_color(CategoryColor.DARKGREEN)
my_category.delete() # oops!
```
## Utils
#### Pagination
When using certain methods, it is possible that you request more items than the api can return in a single api call.
In this case the Api, returns a "next link" url where you can pull more data.
When this is the case, the methods in this library will return a `Pagination` object which abstracts all this into a single iterator.
The pagination object will request "next links" as soon as they are needed.
For example:
```python
mailbox = account.mailbox()
messages = mailbox.get_messages(limit=1500) # the Office 365 and MS Graph API have a 999 items limit returned per api call.
# Here messages is a Pagination instance. It's an Iterator so you can iterate over.
# The first 999 iterations will be normal list iterations, returning one item at a time.
# When the iterator reaches the 1000 item, the Pagination instance will call the api again requesting exactly 500 items
# or the items specified in the batch parameter (see later).
for message in messages:
print(message.subject)
```
When using certain methods you will have the option to specify not only a limit option (the number of items to be returned) but a batch option.
This option will indicate the method to request data to the api in batches until the limit is reached or the data consumed.
This is usefull when you want to optimize memory or network latency.
For example:
```python
messages = mailbox.get_messages(limit=100, batch=25)
# messages here is a Pagination instance
# when iterating over it will call the api 4 times (each requesting 25 items).
for message in messages: # 100 loops with 4 requests to the api server
print(message.subject)
```
#### The Query helper
When using the Office 365 API you can filter, order, select, expand or search on some fields.
This filtering is tedious as is using [Open Data Protocol (OData)](http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part2-url-conventions/odata-v4.0-errata03-os-part2-url-conventions-complete.html).
Every `ApiComponent` (such as `MailBox`) implements a new_query method that will return a `Query` instance.
This `Query` instance can handle the filtering, sorting, selecting, expanding and search very easily.
For example:
```python
query = mailbox.new_query() # you can use the shorthand: mailbox.q()
query = query.on_attribute('subject').contains('george best').chain('or').startswith('quotes')
# 'created_date_time' will automatically be converted to the protocol casing.
# For example when using MS Graph this will become 'createdDateTime'.
query = query.chain('and').on_attribute('created_date_time').greater(datetime(2018, 3, 21))
print(query)
# contains(subject, 'george best') or startswith(subject, 'quotes') and createdDateTime gt '2018-03-21T00:00:00Z'
# note you can pass naive datetimes and those will be converted to you local timezone and then send to the api as UTC in iso8601 format
# To use Query objetcs just pass it to the query parameter:
filtered_messages = mailbox.get_messages(query=query)
```
You can also specify specific data to be retrieved with "select":
```python
# select only some properties for the retrieved messages:
query = mailbox.new_query().select('subject', 'to_recipients', 'created_date_time')
messages_with_selected_properties = mailbox.get_messages(query=query)
```
You can also search content. As said in the graph docs:
> You can currently search only message and person collections. A $search request returns up to 250 results. You cannot use $filter or $orderby in a search request.
> If you do a search on messages and specify only a value without specific message properties, the search is carried out on the default search properties of from, subject, and body.
```python
# searching is the easy part ;)
query = mailbox.q().search('george best is da boss')
messages = mailbox.get_messages(query=query)
```
#### Request Error Handling
Whenever a Request error raises, the connection object will raise an exception.
Then the exception will be captured and logged it to the stdout with it's message, an return Falsy (None, False, [], etc...)
HttpErrors 4xx (Bad Request) and 5xx (Internal Server Error) are considered exceptions and raised also by the connection.
You can tell the `Connection` to not raise http errors by passing `raise_http_errors=False` (defaults to True).
%package help
Summary: Development documents and examples for O365
Provides: python3-O365-doc
%description help
[](https://pepy.tech/project/O365)
[](https://pypi.python.org/pypi/O365)
[](https://pypi.python.org/pypi/O365/)
[](https://travis-ci.org/O365/python-o365)
# O365 - Microsoft Graph and Office 365 API made easy
> Detailed usage documentation is [still in progress](https://o365.github.io/python-o365/latest/index.html)
This project aims to make interacting with Microsoft Graph and Office 365 easy to do in a Pythonic way.
Access to Email, Calendar, Contacts, OneDrive, etc. Are easy to do in a way that feel easy and straight forward to beginners and feels just right to seasoned python programmer.
The project is currently developed and maintained by [Janscas](https://github.com/janscas).
#### Core developers
- [Janscas](https://github.com/janscas)
- [Toben Archer](https://github.com/Narcolapser)
- [Geethanadh](https://github.com/GeethanadhP)
**We are always open to new pull requests!**
#### Rebuilding HTML Docs
- Install `sphinx` python library
`pip install sphinx==2.2.2`
- Run the shell script `build_docs.sh`, or copy the command from the file when using on windows
#### Quick example on sending a message:
```python
from O365 import Account
credentials = ('client_id', 'client_secret')
account = Account(credentials)
m = account.new_message()
m.to.add('to_example@example.com')
m.subject = 'Testing!'
m.body = "George Best quote: I've stopped drinking, but only while I'm asleep."
m.send()
```
### Why choose O365?
- Almost Full Support for MsGraph and Office 365 Rest Api.
- Good Abstraction layer between each Api. Change the api (Graph vs Office365) and don't worry about the api internal implementation.
- Full oauth support with automatic handling of refresh tokens.
- Automatic handling between local datetimes and server datetimes. Work with your local datetime and let this library do the rest.
- Change between different resource with ease: access shared mailboxes, other users resources, SharePoint resources, etc.
- Pagination support through a custom iterator that handles future requests automatically. Request Infinite items!
- A query helper to help you build custom OData queries (filter, order, select and search).
- Modular ApiComponents can be created and built to achieve further functionality.
___
This project was also a learning resource for us. This is a list of not so common python idioms used in this project:
- New unpacking technics: `def method(argument, *, with_name=None, **other_params):`
- Enums: `from enum import Enum`
- Factory paradigm
- Package organization
- Timezone conversion and timezone aware datetimes
- Etc. ([see the code!](https://github.com/O365/python-o365/tree/master/O365))
What follows is kind of a wiki...
## Table of contents
- [Install](#install)
- [Usage](#usage)
- [Authentication](#authentication)
- [Protocols](#protocols)
- [Account Class and Modularity](#account)
- [MailBox](#mailbox)
- [AddressBook](#addressbook)
- [Directory and Users](#directory-and-users)
- [Calendar](#calendar)
- [Tasks](#tasks)
- [OneDrive](#onedrive)
- [Excel](#excel)
- [SharePoint](#sharepoint)
- [Planner](#planner)
- [Outlook Categories](#outlook-categories)
- [Utils](#utils)
## Install
O365 is available on pypi.org. Simply run `pip install O365` to install it.
Requirements: >= Python 3.4
Project dependencies installed by pip:
- requests
- requests-oauthlib
- beatifulsoup4
- stringcase
- python-dateutil
- tzlocal
- pytz
## Usage
The first step to be able to work with this library is to register an application and retrieve the auth token. See [Authentication](#authentication).
It is highly recommended to add the "offline_access" permission and request this scope when authenticating. Otherwise the library will only have access to the user resources for 1 hour. See [Permissions and Scopes](#permissions-and-scopes).
With the access token retrieved and stored you will be able to perform api calls to the service.
A common pattern to check for authentication and use the library is this one:
```python
scopes = ['my_required_scopes'] # you can use scope helpers here (see Permissions and Scopes section)
account = Account(credentials)
if not account.is_authenticated: # will check if there is a token and has not expired
# ask for a login
# console based authentication See Authentication for other flows
account.authenticate(scopes=scopes)
# now we are autheticated
# use the library from now on
# ...
```
## Authentication
You can only authenticate using oauth athentication as Microsoft deprecated basic auth on November 1st 2018.
There are currently three authentication methods:
- [Authenticate on behalf of a user](https://docs.microsoft.com/en-us/graph/auth-v2-user?context=graph%2Fapi%2F1.0&view=graph-rest-1.0):
Any user will give consent to the app to access it's resources.
This oauth flow is called **authorization code grant flow**. This is the default authentication method used by this library.
- [Authenticate on behalf of a user (public)](https://docs.microsoft.com/en-us/graph/auth-v2-user?context=graph%2Fapi%2F1.0&view=graph-rest-1.0):
Same as the former but for public apps where the client secret can't be secured. Client secret is not required.
- [Authenticate with your own identity](https://docs.microsoft.com/en-us/graph/auth-v2-service?context=graph%2Fapi%2F1.0&view=graph-rest-1.0):
This will use your own identity (the app identity). This oauth flow is called **client credentials grant flow**.
> 'Authenticate with your own identity' is not an allowed method for **Microsoft Personal accounts**.
When to use one or the other and requirements:
Topic | On behalf of a user *(auth_flow_type=='authorization')* | On behalf of a user (public) *(auth_flow_type=='public')* | With your own identity *(auth_flow_type=='credentials')*
:---: | :---: | :---: | :---:
**Register the App** | Required | Required | Required
**Requires Admin Consent** | Only on certain advanced permissions | Only on certain advanced permissions | Yes, for everything
**App Permission Type** | Delegated Permissions (on behalf of the user) | Delegated Permissions (on behalf of the user) | Application Permissions
**Auth requirements** | Client Id, Client Secret, Authorization Code | Client Id, Authorization Code | Client Id, Client Secret
**Authentication** | 2 step authentication with user consent | 2 step authentication with user consent | 1 step authentication
**Auth Scopes** | Required | Required | None
**Token Expiration** | 60 Minutes without refresh token or 90 days* | 60 Minutes without refresh token or 90 days* | 60 Minutes*
**Login Expiration** | Unlimited if there is a refresh token and as long as a re| Unlimited if there is a refresh token and as long as a refresh is done within the 90 days | Unlimited
**Resources** | Access the user resources, and any shared resources | Access the user resources, and any shared resources | All Azure AD users the app has access to
**Microsoft Account Type** | Any | Any | Not Allowed for Personal Accounts
**Tenant ID Required** | Defaults to "common" | Defaults to "common" | Required (can't be "common")
**O365 will automatically refresh the token for you on either authentication method. The refresh token lasts 90 days but it's refreshed on each connection so as long as you connect within 90 days you can have unlimited access.*
The `Connection` Class handles the authentication.
#### Oauth Authentication
This section is explained using Microsoft Graph Protocol, almost the same applies to the Office 365 REST API.
##### Authentication Steps
1. To allow authentication you first need to register your application at [Azure App Registrations](https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationsListBlade).
1. Login at [Azure Portal (App Registrations)](https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationsListBlade)
1. Create an app. Set a name.
1. In Supported account types choose "Accounts in any organizational directory and personal Microsoft accounts (e.g. Skype, Xbox, Outlook.com)", if you are using a personal account.
1. Set the redirect uri (Web) to: `https://login.microsoftonline.com/common/oauth2/nativeclient` and click register. This needs to be inserted into the "Redirect URI" text box as simply checking the check box next to this link seems to be insufficent. This is the default redirect uri used by this library, but you can use any other if you want.
1. Write down the Application (client) ID. You will need this value.
1. Under "Certificates & secrets", generate a new client secret. Set the expiration preferably to never. Write down the value of the client secret created now. It will be hidden later on.
1. Under Api Permissions:
- When authenticating "on behalf of a user":
1. add the **delegated permissions** for Microsoft Graph you want (see scopes).
1. It is highly recommended to add "offline_access" permission. If not the user you will have to re-authenticate every hour.
- When authenticating "with your own identity":
1. add the **application permissions** for Microsoft Graph you want.
1. Click on the Grant Admin Consent button (if you have admin permissions) or wait until the admin has given consent to your application.
As an example, to read and send emails use:
1. Mail.ReadWrite
1. Mail.Send
1. User.Read
1. Then you need to login for the first time to get the access token that will grant access to the user resources.
To authenticate (login) you can use [different authentication interfaces](#different-authentication-interfaces). On the following examples we will be using the Console Based Interface but you can use any one.
- When authenticating on behalf of a user:
> **Important:** In case you can't secure the client secret you can use the auth flow type 'public' which only requires the client id.
1. Instantiate an `Account` object with the credentials (client id and client secret).
1. Call `account.authenticate` and pass the scopes you want (the ones you previously added on the app registration portal).
> Note: when using the "on behalf of a user" authentication, you can pass the scopes to either the `Account` init or to the authenticate method. Either way is correct.
You can pass "protocol scopes" (like: "https://graph.microsoft.com/Calendars.ReadWrite") to the method or use "[scope helpers](https://github.com/O365/python-o365/blob/master/O365/connection.py#L34)" like ("message_all").
If you pass protocol scopes, then the `account` instance must be initialized with the same protocol used by the scopes. By using scope helpers you can abstract the protocol from the scopes and let this library work for you.
Finally, you can mix and match "protocol scopes" with "scope helpers".
Go to the [procotol section](#protocols) to know more about them.
For Example (following the previous permissions added):
```python
from O365 import Account
credentials = ('my_client_id', 'my_client_secret')
# the default protocol will be Microsoft Graph
# the default authentication method will be "on behalf of a user"
account = Account(credentials)
if account.authenticate(scopes=['basic', 'message_all']):
print('Authenticated!')
# 'basic' adds: 'offline_access' and 'https://graph.microsoft.com/User.Read'
# 'message_all' adds: 'https://graph.microsoft.com/Mail.ReadWrite' and 'https://graph.microsoft.com/Mail.Send'
```
When using the "on behalf of the user" authentication method, this method call will print a url that the user must visit to give consent to the app on the required permissions.
The user must then visit this url and give consent to the application. When consent is given, the page will rediret to: "https://login.microsoftonline.com/common/oauth2/nativeclient" by default (you can change this) with a url query param called 'code'.
Then the user must copy the resulting page url and paste it back on the console.
The method will then return True if the login attempt was succesful.
- When authenticating with your own identity:
1. Instantiate an `Account` object with the credentials (client id and client secret), specifying the parameter `auth_flow_type` to *"credentials"*. You also need to provide a 'tenant_id'. You don't need to specify any scopes.
1. Call `account.authenticate`. This call will request a token for you and store it in the backend. No user interaction is needed. The method will store the token in the backend and return True if the authentication succeeded.
For Example:
```python
from O365 import Account
credentials = ('my_client_id', 'my_client_secret')
# the default protocol will be Microsoft Graph
account = Account(credentials, auth_flow_type='credentials', tenant_id='my-tenant-id')
if account.authenticate():
print('Authenticated!')
```
1. At this point you will have an access token stored that will provide valid credentials when using the api.
The access token only lasts **60 minutes**, but the app try will automatically request new access tokens.
When using the "on behalf of a user" authentication method this is accomplished through the refresh tokens (if and only if you added the "offline_access" permission), but note that a refresh token only lasts for 90 days. So you must use it before or you will need to request a new access token again (no new consent needed by the user, just a login).
If your application needs to work for more than 90 days without user interaction and without interacting with the API, then you must implement a periodic call to `Connection.refresh_token` before the 90 days have passed.
**Take care: the access (and refresh) token must remain protected from unauthorized users.**
Under the "on behalf of a user" authentication method, if you change the scope requested, then the current token won't work, and you will need the user to give consent again on the application to gain access to the new scopes requested.
##### Different Authentication Interfaces
To acomplish the authentication you can basically use different approaches.
The following apply to the "on behalf of a user" authentication method as this is 2-step authentication flow.
For the "with your own identity" authentication method, you can just use `account.authenticate` as it's not going to require a console input.
1. Console based authentication interface:
You can authenticate using a console. The best way to achieve this is by using the `authenticate` method of the `Account` class.
```python
account = Account(credentials)
account.authenticate(scopes=['basic', 'message_all'])
```
The `authenticate` method will print into the console a url that you will have to visit to achieve authentication.
Then after visiting the link and authenticate you will have to paste back the resulting url into the console.
The method will return `True` and print a message if it was succesful.
**Tip:** When using MacOs the console is limited to 1024 characters. If your url has multiple scopes it can exceed this limit. To solve this. Just `import readline` a the top of your script.
1. Web app based authentication interface:
You can authenticate your users in a web environment by following this steps:
1. First ensure you are using an appropiate TokenBackend to store the auth tokens (See Token storage below).
1. From a handler redirect the user to the Microsoft login url. Provide a callback. Store the state.
1. From the callback handler complete the authentication with the state and other data.
The following example is done using Flask.
```python
@route('/stepone')
def auth_step_one():
callback = 'my absolute url to auth_step_two_callback'
account = Account(credentials)
url, state = account.con.get_authorization_url(requested_scopes=my_scopes,
redirect_uri=callback)
# the state must be saved somewhere as it will be needed later
my_db.store_state(state) # example...
return redirect(url)
@route('/steptwo')
def auth_step_two_callback():
account = Account(credentials)
# retreive the state saved in auth_step_one
my_saved_state = my_db.get_state() # example...
# rebuild the redirect_uri used in auth_step_one
callback = 'my absolute url to auth_step_two_callback'
result = account.con.request_token(request.url,
state=my_saved_state,
redirect_uri=callback)
# if result is True, then authentication was succesful
# and the auth token is stored in the token backend
if result:
return render_template('auth_complete.html')
# else ....
```
1. Other authentication interfaces:
Finally you can configure any other flow by using `connection.get_authorization_url` and `connection.request_token` as you want.
##### Permissions and Scopes:
###### Permissions
When using oauth, you create an application and allow some resources to be accessed and used by its users.
These resources are managed with permissions. These can either be delegated (on behalf of a user) or aplication permissions.
The former are used when the authentication method is "on behalf of a user". Some of these require administrator consent.
The latter when using the "with your own identity" authentication method. All of these require administrator consent.
###### Scopes
The scopes only matter when using the "on behalf of a user" authentication method.
> Note: You only need the scopes when login as those are kept stored within the token on the token backend.
The user of this library can then request access to one or more of this resources by providing scopes to the oauth provider.
> Note: If you latter on change the scopes requested, the current token will be invaled and you will have to re-authenticate. The user that logins will be asked for consent.
For example your application can have Calendar.Read, Mail.ReadWrite and Mail.Send permissions, but the application can request access only to the Mail.ReadWrite and Mail.Send permission.
This is done by providing scopes to the `Account` instance or `account.authenticate` method like so:
```python
from O365 import Account
credentials = ('client_id', 'client_secret')
scopes = ['https://graph.microsoft.com/Mail.ReadWrite', 'https://graph.microsoft.com/Mail.Send']
account = Account(credentials, scopes=scopes)
account.authenticate()
# The latter is exactly the same as passing scopes to the authenticate method like so:
# account = Account(credentials)
# account.authenticate(scopes=scopes)
```
Scope implementation depends on the protocol used. So by using protocol data you can automatically set the scopes needed.
This is implemented by using 'scope helpers'. Those are little helpers that group scope functionality and abstract the protocol used.
Scope Helper | Scopes included
:--- | :---
basic | 'offline_access' and 'User.Read'
mailbox | 'Mail.Read'
mailbox_shared | 'Mail.Read.Shared'
mailbox_settings | 'MailboxSettings.ReadWrite'
message_send | 'Mail.Send'
message_send_shared | 'Mail.Send.Shared'
message_all | 'Mail.ReadWrite' and 'Mail.Send'
message_all_shared | 'Mail.ReadWrite.Shared' and 'Mail.Send.Shared'
address_book | 'Contacts.Read'
address_book_shared | 'Contacts.Read.Shared'
address_book_all | 'Contacts.ReadWrite'
address_book_all_shared | 'Contacts.ReadWrite.Shared'
calendar | 'Calendars.Read'
calendar_shared | 'Calendars.Read.Shared'
calendar_all | 'Calendars.ReadWrite'
calendar_shared_all | 'Calendars.ReadWrite.Shared'
tasks | 'Tasks.Read'
tasks_all | 'Tasks.ReadWrite'
users | 'User.ReadBasic.All'
onedrive | 'Files.Read.All'
onedrive_all | 'Files.ReadWrite.All'
sharepoint | 'Sites.Read.All'
sharepoint_dl | 'Sites.ReadWrite.All'
You can get the same scopes as before using protocols and scope helpers like this:
```python
protocol_graph = MSGraphProtocol()
scopes_graph = protocol.get_scopes_for('message all')
# scopes here are: ['https://graph.microsoft.com/Mail.ReadWrite', 'https://graph.microsoft.com/Mail.Send']
account = Account(credentials, scopes=scopes_graph)
```
```python
protocol_office = MSOffice365Protocol()
scopes_office = protocol.get_scopes_for('message all')
# scopes here are: ['https://outlook.office.com/Mail.ReadWrite', 'https://outlook.office.com/Mail.Send']
account = Account(credentials, scopes=scopes_office)
```
> Note: When passing scopes at the `Account` initialization or on the `account.authenticate` method, the scope helpers are autommatically converted to the protocol flavor.
>Those are the only places where you can use scope helpers. Any other object using scopes (such as the `Connection` object) expects scopes that are already set for the protocol.
##### Token storage:
When authenticating you will retrieve oauth tokens. If you don't want a one time access you will have to store the token somewhere.
O365 makes no assumptions on where to store the token and tries to abstract this from the library usage point of view.
You can choose where and how to store tokens by using the proper Token Backend.
**Take care: the access (and refresh) token must remain protected from unauthorized users.**
The library will call (at different stages) the token backend methods to load and save the token.
Methods that load tokens:
- `account.is_authenticated` property will try to load the token if is not already loaded.
- `connection.get_session`: this method is called when there isn't a request session set. By default it will not try to load the token. Set `load_token=True` to load it.
Methods that stores tokens:
- `connection.request_token`: by default will store the token, but you can set `store_token=False` to avoid it.
- `connection.refresh_token`: by default will store the token. To avoid it change `connection.store_token` to False. This however it's a global setting (that only affects the `refresh_token` method). If you only want the next refresh operation to not store the token you will have to set it back to True afterwards.
To store the token you will have to provide a properly configured TokenBackend.
Actually there are only two implemented (but you can easely implement more like a CookieBackend, RedisBackend, etc.):
- `FileSystemTokenBackend` (Default backend): Stores and retrieves tokens from the file system. Tokens are stored as files.
- `FirestoreTokenBackend`: Stores and retrives tokens from a Google Firestore Datastore. Tokens are stored as documents within a collection.
For example using the FileSystem Token Backend:
```python
from O365 import Account, FileSystemTokenBackend
credentials = ('id', 'secret')
# this will store the token under: "my_project_folder/my_folder/my_token.txt".
# you can pass strings to token_path or Path instances from pathlib
token_backend = FileSystemTokenBackend(token_path='my_folder', token_filename='my_token.txt')
account = Account(credentials, token_backend=token_backend)
# This account instance tokens will be stored on the token_backend configured before.
# You don't have to do anything more
# ...
```
And now using the same example using FirestoreTokenBackend:
```python
from O365 import Account
from O365.utils import FirestoreBackend
from google.cloud import firestore
credentials = ('id', 'secret')
# this will store the token on firestore under the tokens collection on the defined doc_id.
# you can pass strings to token_path or Path instances from pathlib
user_id = 'whatever the user id is' # used to create the token document id
document_id = 'token_{}'.format(user_id) # used to uniquely store this token
token_backend = FirestoreBackend(client=firestore.Client(), collection='tokens', doc_id=document_id)
account = Account(credentials, token_backend=token_backend)
# This account instance tokens will be stored on the token_backend configured before.
# You don't have to do anything more
# ...
```
To implement a new TokenBackend:
1. Subclass `BaseTokenBackend`
1. Implement the following methods:
- `__init__` (don't forget to call `super().__init__`)
- `load_token`: this should load the token from the desired backend and return a `Token` instance or None
- `save_token`: this should store the `self.token` in the desired backend.
- Optionally you can implement: `check_token`, `delete_token` and `should_refresh_token`
The `should_refresh_token` method is intended to be implemented for environments where multiple Connection instances are running on paralel.
This method should check if it's time to refresh the token or not.
The chosen backend can store a flag somewhere to answer this question.
This can avoid race conditions between different instances trying to refresh the token at once, when only one should make the refresh.
The method should return three posible values:
- **True**: then the Connection will refresh the token.
- **False**: then the Connection will NOT refresh the token.
- **None**: then this method already executed the refresh and therefore the Connection does not have to.
By default this always returns True as it's asuming there is are no parallel connections running at once.
There are two examples of this method in the examples folder [here](https://github.com/O365/python-o365/blob/master/examples/token_backends.py).
## Protocols
Protocols handles the aspects of communications between different APIs.
This project uses either the Microsoft Graph APIs (by default) or the Office 365 APIs.
But, you can use many other Microsoft APIs as long as you implement the protocol needed.
You can use one or the other:
- `MSGraphProtocol` to use the [Microsoft Graph API](https://developer.microsoft.com/en-us/graph/docs/concepts/overview)
- `MSOffice365Protocol` to use the [Office 365 API](https://msdn.microsoft.com/en-us/office/office365/api/api-catalog)
Both protocols are similar but consider the following:
Reasons to use `MSGraphProtocol`:
- It is the recommended Protocol by Microsoft.
- It can access more resources over Office 365 (for example OneDrive)
Reasons to use `MSOffice365Protocol`:
- It can send emails with attachments up to 150 MB. MSGraph only allows 4MB on each request (UPDATE: Starting 22 October'19 you can [upload files up to 150MB with MSGraphProtocol **beta** version](https://developer.microsoft.com/en-us/office/blogs/attaching-large-files-to-outlook-messages-in-microsoft-graph-preview/))
The default protocol used by the `Account` Class is `MSGraphProtocol`.
You can implement your own protocols by inheriting from `Protocol` to communicate with other Microsoft APIs.
You can instantiate and use protocols like this:
```python
from O365 import Account, MSGraphProtocol # same as from O365.connection import MSGraphProtocol
# ...
# try the api version beta of the Microsoft Graph endpoint.
protocol = MSGraphProtocol(api_version='beta') # MSGraphProtocol defaults to v1.0 api version
account = Account(credentials, protocol=protocol)
```
##### Resources:
Each API endpoint requires a resource. This usually defines the owner of the data.
Every protocol defaults to resource 'ME'. 'ME' is the user which has given consent, but you can change this behaviour by providing a different default resource to the protocol constructor.
> Note: When using the "with your own identity" authentication method the resource 'ME' is overwritten to be blank as the authentication method already states that you are login with your own identity.
For example when accessing a shared mailbox:
```python
# ...
account = Account(credentials=my_credentials, main_resource='shared_mailbox@example.com')
# Any instance created using account will inherit the resource defined for account.
```
This can be done however at any point. For example at the protocol level:
```python
# ...
protocol = MSGraphProtocol(default_resource='shared_mailbox@example.com')
account = Account(credentials=my_credentials, protocol=protocol)
# now account is accesing the shared_mailbox@example.com in every api call.
shared_mailbox_messages = account.mailbox().get_messages()
```
Instead of defining the resource used at the account or protocol level, you can provide it per use case as follows:
```python
# ...
account = Account(credentials=my_credentials) # account defaults to 'ME' resource
mailbox = account.mailbox('shared_mailbox@example.com') # mailbox is using 'shared_mailbox@example.com' resource instead of 'ME'
# or:
message = Message(parent=account, main_resource='shared_mailbox@example.com') # message is using 'shared_mailbox@example.com' resource
```
Usually you will work with the default 'ME' resource, but you can also use one of the following:
- **'me'**: the user which has given consent. the default for every protocol. Overwritten when using "with your own identity" authentication method (Only available on the authorization auth_flow_type).
- **'user:user@domain.com'**: a shared mailbox or a user account for which you have permissions. If you don't provide 'user:' will be infered anyways.
- **'site:sharepoint-site-id'**: a sharepoint site id.
- **'group:group-site-id'**: a office365 group id.
By setting the resource prefix (such as **'user:'** or **'group:'**) you help the library understand the type of resource. You can also pass it like 'users/example@exampl.com'. Same applies to the other resource prefixes.
## Account Class and Modularity <a name="account"></a>
Usually you will only need to work with the `Account` Class. This is a wrapper around all functionality.
But you can also work only with the pieces you want.
For example, instead of:
```python
from O365 import Account
account = Account(('client_id', 'client_secret'))
message = account.new_message()
# ...
mailbox = account.mailbox()
# ...
```
You can work only with the required pieces:
```python
from O365 import Connection, MSGraphProtocol
from O365.message import Message
from O365.mailbox import MailBox
protocol = MSGraphProtocol()
scopes = ['...']
con = Connection(('client_id', 'client_secret'), scopes=scopes)
message = Message(con=con, protocol=protocol)
# ...
mailbox = MailBox(con=con, protocol=protocol)
message2 = Message(parent=mailbox) # message will inherit the connection and protocol from mailbox when using parent.
# ...
```
It's also easy to implement a custom Class.
Just Inherit from `ApiComponent`, define the endpoints, and use the connection to make requests. If needed also inherit from Protocol to handle different comunications aspects with the API server.
```python
from O365.utils import ApiComponent
class CustomClass(ApiComponent):
_endpoints = {'my_url_key': '/customendpoint'}
def __init__(self, *, parent=None, con=None, **kwargs):
# connection is only needed if you want to communicate with the api provider
self.con = parent.con if parent else con
protocol = parent.protocol if parent else kwargs.get('protocol')
main_resource = parent.main_resource
super().__init__(protocol=protocol, main_resource=main_resource)
# ...
def do_some_stuff(self):
# self.build_url just merges the protocol service_url with the enpoint passed as a parameter
# to change the service_url implement your own protocol inherinting from Protocol Class
url = self.build_url(self._endpoints.get('my_url_key'))
my_params = {'param1': 'param1'}
response = self.con.get(url, params=my_params) # note the use of the connection here.
# handle response and return to the user...
# the use it as follows:
from O365 import Connection, MSGraphProtocol
protocol = MSGraphProtocol() # or maybe a user defined protocol
con = Connection(('client_id', 'client_secret'), scopes=protocol.get_scopes_for(['...']))
custom_class = CustomClass(con=con, protocol=protocol)
custom_class.do_some_stuff()
```
## MailBox
Mailbox groups the funcionality of both the messages and the email folders.
These are the scopes needed to work with the `MailBox` and `Message` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*Mail.Read* | *mailbox* | To only read my mailbox
*Mail.Read.Shared* | *mailbox_shared* | To only read another user / shared mailboxes
*Mail.Send* | *message_send, message_all* | To only send message
*Mail.Send.Shared* | *message_send_shared, message_all_shared* | To only send message as another user / shared mailbox
*Mail.ReadWrite* | *message_all* | To read and save messages in my mailbox
*MailboxSettings.ReadWrite* | *mailbox_settings* | To read and write suer mailbox settings
```python
mailbox = account.mailbox()
inbox = mailbox.inbox_folder()
for message in inbox.get_messages():
print(message)
sent_folder = mailbox.sent_folder()
for message in sent_folder.get_messages():
print(message)
m = mailbox.new_message()
m.to.add('to_example@example.com')
m.body = 'George Best quote: In 1969 I gave up women and alcohol - it was the worst 20 minutes of my life.'
m.save_draft()
```
#### Email Folder
Represents a `Folder` within your email mailbox.
You can get any folder in your mailbox by requesting child folders or filtering by name.
```python
mailbox = account.mailbox()
archive = mailbox.get_folder(folder_name='archive') # get a folder with 'archive' name
child_folders = archive.get_folders(25) # get at most 25 child folders of 'archive' folder
for folder in child_folders:
print(folder.name, folder.parent_id)
new_folder = archive.create_child_folder('George Best Quotes')
```
#### Message
An email object with all its data and methods.
Creating a draft message is as easy as this:
```python
message = mailbox.new_message()
message.to.add(['example1@example.com', 'example2@example.com'])
message.sender.address = 'my_shared_account@example.com' # changing the from address
message.body = 'George Best quote: I might go to Alcoholics Anonymous, but I think it would be difficult for me to remain anonymous'
message.attachments.add('george_best_quotes.txt')
message.save_draft() # save the message on the cloud as a draft in the drafts folder
```
Working with saved emails is also easy:
```python
query = mailbox.new_query().on_attribute('subject').contains('george best') # see Query object in Utils
messages = mailbox.get_messages(limit=25, query=query)
message = messages[0] # get the first one
message.mark_as_read()
reply_msg = message.reply()
if 'example@example.com' in reply_msg.to: # magic methods implemented
reply_msg.body = 'George Best quote: I spent a lot of money on booze, birds and fast cars. The rest I just squandered.'
else:
reply_msg.body = 'George Best quote: I used to go missing a lot... Miss Canada, Miss United Kingdom, Miss World.'
reply_msg.send()
```
##### Sending Inline Images
You can send inline images by doing this:
```python
# ...
msg = account.new_message()
msg.to.add('george@best.com')
msg.attachments.add('my_image.png')
att = msg.attachments[0] # get the attachment object
# this is super important for this to work.
att.is_inline = True
att.content_id = 'image.png'
# notice we insert an image tag with source to: "cid:{content_id}"
body = """
<html>
<body>
<strong>There should be an image here:</strong>
<p>
<img src="cid:image.png">
</p>
</body>
</html>
"""
msg.body = body
msg.send()
```
##### Retrieving Message Headers
You can retrieve message headers by doing this:
```python
# ...
mb = account.mailbox()
msg = mb.get_message(query=mb.q().select('internet_message_headers'))
print(msg.message_headers) # returns a list of dicts.
```
Note that only message headers and other properties added to the select statement will be present.
##### Saving as EML
Messages and attached messages can be saved as *.eml.
- Save message as "eml":
```python
msg.save_as_eml(to_path=Path('my_saved_email.eml'))
```
- Save attached message as "eml":
Carefull: there's no way to identify that an attachment is in fact a message. You can only check if the attachment.attachment_type == 'item'.
if is of type "item" then it can be a message (or an event, etc...). You will have to determine this yourself.
```python
msg_attachment = msg.attachments[0] # the first attachment is attachment.attachment_type == 'item' and I know it's a message.
msg.attachments.save_as_eml(msg_attachment, to_path=Path('my_saved_email.eml'))
```
#### Mailbox Settings
The mailbox settings and associated methods.
Retrieve and update mailbox auto reply settings:
```python
from O365.mailbox import AutoReplyStatus, ExternalAudience
mailboxsettings = mailbox.get_settings()
ars = mailboxsettings.automaticrepliessettings
ars.scheduled_startdatetime = start # Sets the start date/time
ars.scheduled_enddatetime = end # Sets the end date/time
ars.status = AutoReplyStatus.SCHEDULED # DISABLED/SCHEDULED/ALWAYSENABLED - Uses start/end date/time if scheduled.
ars.external_audience = ExternalAudience.NONE # NONE/CONTACTSONLY/ALL
ars.internal_reply_message = "ARS Internal" # Internal message
ars.external_reply_message = "ARS External" # External message
mailboxsettings.save()
```
Alternatively to enable and disable
```python
mailboxsettings.save()
mailbox.set_automatic_reply(
"Internal",
"External",
scheduled_start_date_time=start, # Status will be 'scheduled' if start/end supplied, otherwise 'alwaysEnabled'
scheduled_end_date_time=end,
externalAudience=ExternalAudience.NONE, # Defaults to ALL
)
mailbox.set_disable_reply()
```
## AddressBook
AddressBook groups the functionality of both the Contact Folders and Contacts. Outlook Distribution Groups are not supported (By the Microsoft API's).
These are the scopes needed to work with the `AddressBook` and `Contact` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*Contacts.Read* | *address_book* | To only read my personal contacts
*Contacts.Read.Shared* | *address_book_shared* | To only read another user / shared mailbox contacts
*Contacts.ReadWrite* | *address_book_all* | To read and save personal contacts
*Contacts.ReadWrite.Shared* | *address_book_all_shared* | To read and save contacts from another user / shared mailbox
*User.ReadBasic.All* | *users* | To only read basic properties from users of my organization (User.Read.All requires administrator consent).
#### Contact Folders
Represents a Folder within your Contacts Section in Office 365.
AddressBook class represents the parent folder (it's a folder itself).
You can get any folder in your address book by requesting child folders or filtering by name.
```python
address_book = account.address_book()
contacts = address_book.get_contacts(limit=None) # get all the contacts in the Personal Contacts root folder
work_contacts_folder = address_book.get_folder(folder_name='Work Contacts') # get a folder with 'Work Contacts' name
message_to_all_contats_in_folder = work_contacts_folder.new_message() # creates a draft message with all the contacts as recipients
message_to_all_contats_in_folder.subject = 'Hallo!'
message_to_all_contats_in_folder.body = """
George Best quote:
If you'd given me the choice of going out and beating four men and smashing a goal in
from thirty yards against Liverpool or going to bed with Miss World,
it would have been a difficult choice. Luckily, I had both.
"""
message_to_all_contats_in_folder.send()
# querying folders is easy:
child_folders = address_book.get_folders(25) # get at most 25 child folders
for folder in child_folders:
print(folder.name, folder.parent_id)
# creating a contact folder:
address_book.create_child_folder('new folder')
```
#### The Global Address List
Office 365 API (Nor MS Graph API) has no concept such as the Outlook Global Address List.
However you can use the [Users API](https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/resources/users) to access all the users within your organization.
Without admin consent you can only access a few properties of each user such as name and email and litte more.
You can search by name or retrieve a contact specifying the complete email.
- Basic Permision needed is Users.ReadBasic.All (limit info)
- Full Permision is Users.Read.All but needs admin consent.
To search the Global Address List (Users API):
```python
global_address_list = account.directory()
# for backwards compatibilty only this also works and returns a Directory object:
# global_address_list = account.address_book(address_book='gal')
# start a new query:
q = global_address_list.new_query('display_name')
q.startswith('George Best')
for user in global_address_list.get_users(query=q):
print(user)
```
To retrieve a contact by their email:
```python
contact = global_address_list.get_user('example@example.com')
```
#### Contacts
Everything returned from an `AddressBook` instance is a `Contact` instance.
Contacts have all the information stored as attributes
Creating a contact from an `AddressBook`:
```python
new_contact = address_book.new_contact()
new_contact.name = 'George Best'
new_contact.job_title = 'football player'
new_contact.emails.add('george@best.com')
new_contact.save() # saved on the cloud
message = new_contact.new_message() # Bonus: send a message to this contact
# ...
new_contact.delete() # Bonus: deteled from the cloud
```
## Directory and Users
The Directory object can retrieve users.
A User instance contains by default the [basic properties of the user](https://docs.microsoft.com/en-us/graph/api/user-list?view=graph-rest-1.0&tabs=http#optional-query-parameters).
If you want to include more, you will have to select the desired properties manually.
Check [The Global Address List](#the-global-address-list) for further information.
```python
directory = account.directory()
for user in directory.get_users():
print(user)
```
## Calendar
The calendar and events functionality is group in a `Schedule` object.
A `Schedule` instance can list and create calendars. It can also list or create events on the default user calendar.
To use other calendars use a `Calendar` instance.
These are the scopes needed to work with the `Schedule`, `Calendar` and `Event` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*Calendars.Read* | *calendar* | To only read my personal calendars
*Calendars.Read.Shared* | *calendar_shared* | To only read another user / shared mailbox calendars
*Calendars.ReadWrite* | *calendar_all* | To read and save personal calendars
*Calendars.ReadWrite.Shared* | *calendar_shared_all* | To read and save calendars from another user / shared mailbox
Working with the `Schedule` instance:
```python
import datetime as dt
# ...
schedule = account.schedule()
calendar = schedule.get_default_calendar()
new_event = calendar.new_event() # creates a new unsaved event
new_event.subject = 'Recruit George Best!'
new_event.location = 'England'
# naive datetimes will automatically be converted to timezone aware datetime
# objects using the local timezone detected or the protocol provided timezone
new_event.start = dt.datetime(2019, 9, 5, 19, 45)
# so new_event.start becomes: datetime.datetime(2018, 9, 5, 19, 45, tzinfo=<DstTzInfo 'Europe/Paris' CEST+2:00:00 DST>)
new_event.recurrence.set_daily(1, end=dt.datetime(2019, 9, 10))
new_event.remind_before_minutes = 45
new_event.save()
```
Working with `Calendar` instances:
```python
calendar = schedule.get_calendar(calendar_name='Birthdays')
calendar.name = 'Football players birthdays'
calendar.update()
q = calendar.new_query('start').greater_equal(dt.datetime(2018, 5, 20))
q.chain('and').on_attribute('end').less_equal(dt.datetime(2018, 5, 24))
birthdays = calendar.get_events(query=q, include_recurring=True) # include_recurring=True will include repeated events on the result set.
for event in birthdays:
if event.subject == 'George Best Birthday':
# He died in 2005... but we celebrate anyway!
event.accept("I'll attend!") # send a response accepting
else:
event.decline("No way I'm comming, I'll be in Spain", send_response=False) # decline the event but don't send a reponse to the organizer
```
#### Notes regarding Calendars and Events:
1. Include_recurring=True:
> It's important to know that when querying events with `include_recurring=True` (which is the default), it is required that you must provide a query parameter with the start and end attributes defined.
> Unlike when using `include_recurring=False` those attributes will NOT filter the data based on the operations you set on the query (greater_equal, less, etc.) but just filter the events start datetime between the provided start and end datetimes.
1. Shared Calendars:
There are some known issues when working with [shared calendars](https://docs.microsoft.com/en-us/graph/known-issues#calendars) in Microsoft Graph.
1. Event attachments:
For some unknow reason, microsoft does not allow to upload an attachment at the event creation time (as opposed with message attachments).
See [this](https://stackoverflow.com/questions/46438302/office365-rest-api-creating-a-calendar-event-with-attachments?rq=1).
So, to upload attachments to Events, first save the event, then attach the message and save again.
## Tasks
The tasks functionality is grouped in a `ToDo` object.
A `ToDo` instance can list and create task folders. It can also list or create tasks on the default user folder. To use other folders use a `Folder` instance.
These are the scopes needed to work with the `ToDo`, `Folder` and `Task` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*Tasks.Read* | *tasks* | To only read my personal tasks
*Tasks.ReadWrite* | *tasks_all* | To read and save personal calendars
Working with the `ToDo` instance:
```python
import datetime as dt
# ...
todo = account.tasks()
#list current tasks
folder = todo.get_default_folder()
new_task = folder.new_task() # creates a new unsaved task
new_task.subject = 'Send contract to George Best'
new_task.due = dt.datetime(2020, 9, 25, 18, 30)
new_task.save()
#some time later....
new_task.mark_completed()
new_task.save()
# naive datetimes will automatically be converted to timezone aware datetime
# objects using the local timezone detected or the protocol provided timezone
# as with the Calendar functionality
```
Working with `Folder` instances:
```python
#create a new folder
new_folder = todo.new_folder('Defenders')
#rename a folder
folder = todo.get_folder(folder_name='Strikers')
folder.name = 'Forwards'
folder.update()
#list current tasks
task_list = folder.get_tasks()
for task in task_list:
print(task)
print('')
```
## OneDrive
The `Storage` class handles all functionality around One Drive and Document Library Storage in SharePoint.
The `Storage` instance allows to retrieve `Drive` instances which handles all the Files and Folders from within the selected `Storage`.
Usually you will only need to work with the default drive. But the `Storage` instances can handle multiple drives.
A `Drive` will allow you to work with Folders and Files.
These are the scopes needed to work with the `Storage`, `Drive` and `DriveItem` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*Files.Read* | | To only read my files
*Files.Read.All* | *onedrive* | To only read all the files the user has access
*Files.ReadWrite* | | To read and save my files
*Files.ReadWrite.All* | *onedrive_all* | To read and save all the files the user has access
```python
account = Account(credentials=my_credentials)
storage = account.storage() # here we get the storage instance that handles all the storage options.
# list all the drives:
drives = storage.get_drives()
# get the default drive
my_drive = storage.get_default_drive() # or get_drive('drive-id')
# get some folders:
root_folder = my_drive.get_root_folder()
attachments_folder = my_drive.get_special_folder('attachments')
# iterate over the first 25 items on the root folder
for item in root_folder.get_items(limit=25):
if item.is_folder:
print(list(item.get_items(2))) # print the first to element on this folder.
elif item.is_file:
if item.is_photo:
print(item.camera_model) # print some metadata of this photo
elif item.is_image:
print(item.dimensions) # print the image dimensions
else:
# regular file:
print(item.mime_type) # print the mime type
```
Both Files and Folders are DriveItems. Both Image and Photo are Files, but Photo is also an Image. All have some different methods and properties.
Take care when using 'is_xxxx'.
When copying a DriveItem the api can return a direct copy of the item or a pointer to a resource that will inform on the progress of the copy operation.
```python
# copy a file to the documents special folder
documents_folder = my_drive.get_special_folder('documents')
files = my_drive.search('george best quotes', limit=1)
if files:
george_best_quotes = files[0]
operation = george_best_quotes.copy(target=documents_folder) # operation here is an instance of CopyOperation
# to check for the result just loop over check_status.
# check_status is a generator that will yield a new status and progress until the file is finally copied
for status, progress in operation.check_status(): # if it's an async operations, this will request to the api for the status in every loop
print('{} - {}'.format(status, progress)) # prints 'in progress - 77.3' until finally completed: 'completed - 100.0'
copied_item = operation.get_item() # the copy operation is completed so you can get the item.
if copied_item:
copied_item.delete() # ... oops!
```
You can also work with share permissions:
```python
current_permisions = file.get_permissions() # get all the current permissions on this drive_item (some may be inherited)
# share with link
permission = file.share_with_link(share_type='edit')
if permission:
print(permission.share_link) # the link you can use to share this drive item
# share with invite
permission = file.share_with_invite(recipients='george_best@best.com', send_email=True, message='Greetings!!', share_type='edit')
if permission:
print(permission.granted_to) # the person you share this item with
```
You can also:
```python
# download files:
file.download(to_path='/quotes/')
# upload files:
# if the uploaded file is bigger than 4MB the file will be uploaded in chunks of 5 MB until completed.
# this can take several requests and can be time consuming.
uploaded_file = folder.upload_file(item='path_to_my_local_file')
# restore versions:
versions = file.get_versions()
for version in versions:
if version.name == '2.0':
version.restore() # restore the version 2.0 of this file
# ... and much more ...
```
## Excel
You can interact with new excel files (.xlsx) stored in OneDrive or a SharePoint Document Library.
You can retrieve workbooks, worksheets, tables, and even cell data.
You can also write to any excel online.
To work with excel files, first you have to retrieve a `File` instance using the OneDrive or SharePoint functionallity.
The scopes needed to work with the `WorkBook` and Excel related classes are the same used by OneDrive.
This is how you update a cell value:
```python
from O365.excel import WorkBook
# given a File instance that is a xlsx file ...
excel_file = WorkBook(my_file_instance) # my_file_instance should be an instance of File.
ws = excel_file.get_worksheet('my_worksheet')
cella1 = ws.get_range('A1')
cella1.values = 35
cella1.update()
```
#### Workbook Sessions
When interacting with excel, you can use a workbook session to efficiently make changes in a persistent or nonpersistent way.
This sessions become usefull if you perform numerous changes to the excel file.
The default is to use a session in a persistent way.
Sessions expire after some time of inactivity. When working with persistent sessions, new sessions will automatically be created when old ones expire.
You can however change this when creating the `Workbook` instance:
```python
excel_file = WorkBook(my_file_instance, use_session=False, persist=False)
```
#### Available Objects
After creating the `WorkBook` instance you will have access to the following objects:
- WorkSheet
- Range and NamedRange
- Table, TableColumn and TableRow
- RangeFormat (to format ranges)
- Charts (not available for now)
Some examples:
Set format for a given range
```python
# ...
my_range = ws.get_range('B2:C10')
fmt = myrange.get_format()
fmt.font.bold = True
fmt.update()
```
Autofit Columns:
```python
ws.get_range('B2:C10').get_format().auto_fit_columns()
```
Get values from Table:
```python
table = ws.get_table('my_table')
column = table.get_column_at_index(1)
values = column.values[0] # values returns a two dimensional array.
```
## SharePoint
The SharePoint api is done but there are no docs yet. Look at the sharepoint.py file to get insights.
These are the scopes needed to work with the `SharePoint` and `Site` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*Sites.Read.All* | *sharepoint* | To only read sites, lists and items
*Sites.ReadWrite.All* | *sharepoint_dl* | To read and save sites, lists and items
## Planner
The planner api is done but there are no docs yet. Look at the planner.py file to get insights.
The planner functionality requires Administrator Permission.
## Outlook Categories
You can retrive, update, create and delete outlook categories.
These categories can be used to categorize Messages, Events and Contacts.
These are the scopes needed to work with the `SharePoint` and `Site` classes.
Raw Scope | Included in Scope Helper | Description
:---: | :---: | ---
*MailboxSettings.Read* | *-* | To only read outlook settingss
*MailboxSettings.ReadWrite* | *settings_all* | To read and write outlook settings
Example:
```python
from O365.category import CategoryColor
oc = account.outlook_categories()
categories = oc.get_categories()
for category in categories:
print(category.name, category.color)
my_category = oc.create_category('Important Category', color=CategoryColor.RED)
my_category.update_color(CategoryColor.DARKGREEN)
my_category.delete() # oops!
```
## Utils
#### Pagination
When using certain methods, it is possible that you request more items than the api can return in a single api call.
In this case the Api, returns a "next link" url where you can pull more data.
When this is the case, the methods in this library will return a `Pagination` object which abstracts all this into a single iterator.
The pagination object will request "next links" as soon as they are needed.
For example:
```python
mailbox = account.mailbox()
messages = mailbox.get_messages(limit=1500) # the Office 365 and MS Graph API have a 999 items limit returned per api call.
# Here messages is a Pagination instance. It's an Iterator so you can iterate over.
# The first 999 iterations will be normal list iterations, returning one item at a time.
# When the iterator reaches the 1000 item, the Pagination instance will call the api again requesting exactly 500 items
# or the items specified in the batch parameter (see later).
for message in messages:
print(message.subject)
```
When using certain methods you will have the option to specify not only a limit option (the number of items to be returned) but a batch option.
This option will indicate the method to request data to the api in batches until the limit is reached or the data consumed.
This is usefull when you want to optimize memory or network latency.
For example:
```python
messages = mailbox.get_messages(limit=100, batch=25)
# messages here is a Pagination instance
# when iterating over it will call the api 4 times (each requesting 25 items).
for message in messages: # 100 loops with 4 requests to the api server
print(message.subject)
```
#### The Query helper
When using the Office 365 API you can filter, order, select, expand or search on some fields.
This filtering is tedious as is using [Open Data Protocol (OData)](http://docs.oasis-open.org/odata/odata/v4.0/errata03/os/complete/part2-url-conventions/odata-v4.0-errata03-os-part2-url-conventions-complete.html).
Every `ApiComponent` (such as `MailBox`) implements a new_query method that will return a `Query` instance.
This `Query` instance can handle the filtering, sorting, selecting, expanding and search very easily.
For example:
```python
query = mailbox.new_query() # you can use the shorthand: mailbox.q()
query = query.on_attribute('subject').contains('george best').chain('or').startswith('quotes')
# 'created_date_time' will automatically be converted to the protocol casing.
# For example when using MS Graph this will become 'createdDateTime'.
query = query.chain('and').on_attribute('created_date_time').greater(datetime(2018, 3, 21))
print(query)
# contains(subject, 'george best') or startswith(subject, 'quotes') and createdDateTime gt '2018-03-21T00:00:00Z'
# note you can pass naive datetimes and those will be converted to you local timezone and then send to the api as UTC in iso8601 format
# To use Query objetcs just pass it to the query parameter:
filtered_messages = mailbox.get_messages(query=query)
```
You can also specify specific data to be retrieved with "select":
```python
# select only some properties for the retrieved messages:
query = mailbox.new_query().select('subject', 'to_recipients', 'created_date_time')
messages_with_selected_properties = mailbox.get_messages(query=query)
```
You can also search content. As said in the graph docs:
> You can currently search only message and person collections. A $search request returns up to 250 results. You cannot use $filter or $orderby in a search request.
> If you do a search on messages and specify only a value without specific message properties, the search is carried out on the default search properties of from, subject, and body.
```python
# searching is the easy part ;)
query = mailbox.q().search('george best is da boss')
messages = mailbox.get_messages(query=query)
```
#### Request Error Handling
Whenever a Request error raises, the connection object will raise an exception.
Then the exception will be captured and logged it to the stdout with it's message, an return Falsy (None, False, [], etc...)
HttpErrors 4xx (Bad Request) and 5xx (Internal Server Error) are considered exceptions and raised also by the connection.
You can tell the `Connection` to not raise http errors by passing `raise_http_errors=False` (defaults to True).
%prep
%autosetup -n O365-2.0.26
%build
%py3_build
%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
find usr/lib -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
find usr/lib64 -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
find usr/bin -type f -printf "/%h/%f\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
find usr/sbin -type f -printf "/%h/%f\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
find usr/share/man -type f -printf "/%h/%f.gz\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .
%files -n python3-O365 -f filelist.lst
%dir %{python3_sitelib}/*
%files help -f doclist.lst
%{_docdir}/*
%changelog
* Fri Apr 21 2023 Python_Bot <Python_Bot@openeuler.org> - 2.0.26-1
- Package Spec generated
|