aboutsummaryrefslogblamecommitdiffstats
path: root/libemail-engine/e-mail-session-utils.c
blob: 7e1aae3ef87843edf45f9051df85692d92c24e63 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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

















                                                                             



                    

                                 
                           
                                          
 


                                                



                                                                       


                                                                 


                                          
                            








                                  

                                







                                      

                                  
                          
                           




                                          

                                                 
 














                                                        


                                                    













                                                                     
                                     
                                      



                                             












                                                            
           





















































































































                                                                             











                                                                     

                                                                 







































































                                                                      

                                                                          









































                                                                      

                                                                 










































































































                                                                             

                                                                          


































                                                                      

                                   
                                       
                                            

                                     
                                     




                                                                     

                                                            
 
                                                 
 









                                                               
 


                                                                          
 

                                                                 
 




                                                                         
 

                                                                   

                                                                 
 



                                                          
 




                                                                  
                                                       






                                                                               
                 
 
                                    
                                                                         



                               
          











                                                                           
                                                                         











                                                                
                                                                         


























                                                                              


                                                                                            






                                                       


                                                   
 

                                                                
 



                                                        

                                 



                                                                  






                                                                      
                                                            

                                         
                                                                    





                                                                 
                                                                     
                                                     





                                                       


























                                                                         





















                                                                        
                                                                 



                                                               

                                                     



                                                   
                             
                                               


                                                          



                                             

                                            
                                            
 
                          
                     

                                        


                                                                       

                              
                    

 


                                                  





                                                                 
 
                                   




                                 
                                


                                         
                                 

                             
                                                       





                                                               



                                                              



                                                            






                                                                        
                                                                   
















































                                                                         



                                                          



                                                                    

                                                  
                                           

                                         


                                             
                                       
 


                                                                  
                                                                    

                                                                           
                                                       







                                                                           



                                                            



                                                   

                                                                          


                                                                      




                                                
 
                                


















                                                                      
 











































































































































































































































































































































































































































































































































































































































































                                                                                
/*
 * e-mail-session-utils.c
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with the program; if not, see <http://www.gnu.org/licenses/>
 *
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include "e-mail-session-utils.h"

#include <glib/gi18n-lib.h>
#include <libedataserver/libedataserver.h>

#include <libemail-engine/e-mail-folder-utils.h>
#include <libemail-engine/e-mail-utils.h>
#include <libemail-engine/mail-tools.h>

/* X-Mailer header value */
#define X_MAILER ("Evolution " VERSION SUB_VERSION " " VERSION_COMMENT)

/* FIXME: Temporary - remove this after we move filter/ to eds */
#define E_FILTER_SOURCE_OUTGOING "outgoing"

typedef struct _AsyncContext AsyncContext;

struct _AsyncContext {
    CamelFolder *folder;

    CamelMimeMessage *message;
    CamelMessageInfo *info;

    CamelAddress *from;
    CamelAddress *recipients;

    CamelFilterDriver *driver;

    CamelService *transport;

    GCancellable *cancellable;
    gint io_priority;

    /* X-Evolution headers */
    struct _camel_header_raw *xev;

    GPtrArray *post_to_uris;

    EMailLocalFolder local_id;

    gchar *folder_uri;
    gchar *message_uid;
};

static void
async_context_free (AsyncContext *context)
{
    if (context->folder != NULL)
        g_object_unref (context->folder);

    if (context->message != NULL)
        g_object_unref (context->message);

    if (context->info != NULL)
        camel_message_info_free (context->info);

    if (context->from != NULL)
        g_object_unref (context->from);

    if (context->recipients != NULL)
        g_object_unref (context->recipients);

    if (context->driver != NULL)
        g_object_unref (context->driver);

    if (context->transport != NULL)
        g_object_unref (context->transport);

    if (context->cancellable != NULL) {
        camel_operation_pop_message (context->cancellable);
        g_object_unref (context->cancellable);
    }

    if (context->xev != NULL)
        camel_header_raw_clear (&context->xev);

    if (context->post_to_uris != NULL) {
        g_ptr_array_foreach (
            context->post_to_uris, (GFunc) g_free, NULL);
        g_ptr_array_free (context->post_to_uris, TRUE);
    }

    g_free (context->folder_uri);
    g_free (context->message_uid);

    g_slice_free (AsyncContext, context);
}

GQuark
e_mail_error_quark (void)
{
    static GQuark quark = 0;

    if (G_UNLIKELY (quark == 0)) {
        const gchar *string = "e-mail-error-quark";
        quark = g_quark_from_static_string (string);
    }

    return quark;
}

static void
mail_session_append_to_local_folder_thread (GSimpleAsyncResult *simple,
                                            GObject *object,
                                            GCancellable *cancellable)
{
    AsyncContext *context;
    GError *error = NULL;

    context = g_simple_async_result_get_op_res_gpointer (simple);

    e_mail_session_append_to_local_folder_sync (
        E_MAIL_SESSION (object),
        context->local_id, context->message,
        context->info, &context->message_uid,
        cancellable, &error);

    if (error != NULL)
        g_simple_async_result_take_error (simple, error);
}

gboolean
e_mail_session_append_to_local_folder_sync (EMailSession *session,
                                            EMailLocalFolder local_id,
                                            CamelMimeMessage *message,
                                            CamelMessageInfo *info,
                                            gchar **appended_uid,
                                            GCancellable *cancellable,
                                            GError **error)
{
    CamelFolder *folder;
    const gchar *folder_uri;
    gboolean success = FALSE;

    g_return_val_if_fail (E_IS_MAIL_SESSION (session), FALSE);
    g_return_val_if_fail (CAMEL_IS_MIME_MESSAGE (message), FALSE);

    folder_uri = e_mail_session_get_local_folder_uri (session, local_id);
    g_return_val_if_fail (folder_uri != NULL, FALSE);

    folder = e_mail_session_uri_to_folder_sync (
        session, folder_uri, CAMEL_STORE_FOLDER_CREATE,
        cancellable, error);

    if (folder != NULL) {
        success = e_mail_folder_append_message_sync (
            folder, message, info, appended_uid,
            cancellable, error);
        g_object_unref (folder);
    }

    return success;
}

void
e_mail_session_append_to_local_folder (EMailSession *session,
                                       EMailLocalFolder local_id,
                                       CamelMimeMessage *message,
                                       CamelMessageInfo *info,
                                       gint io_priority,
                                       GCancellable *cancellable,
                                       GAsyncReadyCallback callback,
                                       gpointer user_data)
{
    GSimpleAsyncResult *simple;
    AsyncContext *context;

    g_return_if_fail (E_IS_MAIL_SESSION (session));
    g_return_if_fail (CAMEL_IS_MIME_MESSAGE (message));

    context = g_slice_new0 (AsyncContext);
    context->local_id = local_id;
    context->message = g_object_ref (message);

    if (info != NULL)
        context->info = camel_message_info_ref (info);

    simple = g_simple_async_result_new (
        G_OBJECT (session), callback, user_data,
        e_mail_session_append_to_local_folder);

    g_simple_async_result_set_check_cancellable (simple, cancellable);

    g_simple_async_result_set_op_res_gpointer (
        simple, context, (GDestroyNotify) async_context_free);

    g_simple_async_result_run_in_thread (
        simple, mail_session_append_to_local_folder_thread,
        io_priority, cancellable);

    g_object_unref (simple);
}

gboolean
e_mail_session_append_to_local_folder_finish (EMailSession *session,
                                              GAsyncResult *result,
                                              gchar **appended_uid,
                                              GError **error)
{
    GSimpleAsyncResult *simple;
    AsyncContext *context;

    g_return_val_if_fail (
        g_simple_async_result_is_valid (
        result, G_OBJECT (session),
        e_mail_session_append_to_local_folder), FALSE);

    simple = G_SIMPLE_ASYNC_RESULT (result);
    context = g_simple_async_result_get_op_res_gpointer (simple);

    if (appended_uid != NULL) {
        *appended_uid = context->message_uid;
        context->message_uid = NULL;
    }

    /* Assume success unless a GError is set. */
    return !g_simple_async_result_propagate_error (simple, error);
}

static void
mail_session_handle_draft_headers_thread (GSimpleAsyncResult *simple,
                                          EMailSession *session,
                                          GCancellable *cancellable)
{
    AsyncContext *context;
    GError *error = NULL;

    context = g_simple_async_result_get_op_res_gpointer (simple);

    e_mail_session_handle_draft_headers_sync (
        session, context->message, cancellable, &error);

    if (error != NULL)
        g_simple_async_result_take_error (simple, error);
}

gboolean
e_mail_session_handle_draft_headers_sync (EMailSession *session,
                                          CamelMimeMessage *message,
                                          GCancellable *cancellable,
                                          GError **error)
{
    CamelFolder *folder;
    CamelMedium *medium;
    const gchar *folder_uri;
    const gchar *message_uid;
    const gchar *header_name;
    gboolean success;

    g_return_val_if_fail (E_IS_MAIL_SESSION (session), FALSE);
    g_return_val_if_fail (CAMEL_IS_MIME_MESSAGE (message), FALSE);

    medium = CAMEL_MEDIUM (message);

    header_name = "X-Evolution-Draft-Folder";
    folder_uri = camel_medium_get_header (medium, header_name);

    header_name = "X-Evolution-Draft-Message";
    message_uid = camel_medium_get_header (medium, header_name);

    /* Don't report errors about missing X-Evolution-Draft
     * headers.  These headers are optional, so their absence
     * is handled by doing nothing. */
    if (folder_uri == NULL || message_uid == NULL)
        return TRUE;

    folder = e_mail_session_uri_to_folder_sync (
        session, folder_uri, 0, cancellable, error);

    if (folder == NULL)
        return FALSE;

    camel_folder_set_message_flags (
        folder, message_uid,
        CAMEL_MESSAGE_DELETED | CAMEL_MESSAGE_SEEN,
        CAMEL_MESSAGE_DELETED | CAMEL_MESSAGE_SEEN);

    success = camel_folder_synchronize_message_sync (
        folder, message_uid, cancellable, error);

    g_object_unref (folder);

    return success;
}

void
e_mail_session_handle_draft_headers (EMailSession *session,
                                     CamelMimeMessage *message,
                                     gint io_priority,
                                     GCancellable *cancellable,
                                     GAsyncReadyCallback callback,
                                     gpointer user_data)
{
    GSimpleAsyncResult *simple;
    AsyncContext *context;

    g_return_if_fail (E_IS_MAIL_SESSION (session));
    g_return_if_fail (CAMEL_IS_MIME_MESSAGE (message));

    context = g_slice_new0 (AsyncContext);
    context->message = g_object_ref (message);

    simple = g_simple_async_result_new (
        G_OBJECT (session), callback, user_data,
        e_mail_session_handle_draft_headers);

    g_simple_async_result_set_check_cancellable (simple, cancellable);

    g_simple_async_result_set_op_res_gpointer (
        simple, context, (GDestroyNotify) async_context_free);

    g_simple_async_result_run_in_thread (
        simple, (GSimpleAsyncThreadFunc)
        mail_session_handle_draft_headers_thread,
        io_priority, cancellable);

    g_object_unref (simple);
}

gboolean
e_mail_session_handle_draft_headers_finish (EMailSession *session,
                                            GAsyncResult *result,
                                            GError **error)
{
    GSimpleAsyncResult *simple;

    g_return_val_if_fail (
        g_simple_async_result_is_valid (
        result, G_OBJECT (session),
        e_mail_session_handle_draft_headers), FALSE);

    simple = G_SIMPLE_ASYNC_RESULT (result);

    /* Assume success unless a GError is set. */
    return !g_simple_async_result_propagate_error (simple, error);
}

static void
mail_session_handle_source_headers_thread (GSimpleAsyncResult *simple,
                                           EMailSession *session,
                                           GCancellable *cancellable)
{
    AsyncContext *context;
    GError *error = NULL;

    context = g_simple_async_result_get_op_res_gpointer (simple);

    e_mail_session_handle_source_headers_sync (
        session, context->message, cancellable, &error);

    if (error != NULL)
        g_simple_async_result_take_error (simple, error);
}

gboolean
e_mail_session_handle_source_headers_sync (EMailSession *session,
                                           CamelMimeMessage *message,
                                           GCancellable *cancellable,
                                           GError **error)
{
    CamelFolder *folder;
    CamelMedium *medium;
    CamelMessageFlags flags = 0;
    const gchar *folder_uri;
    const gchar *message_uid;
    const gchar *flag_string;
    const gchar *header_name;
    gboolean success;
    guint length, ii;
    gchar **tokens;
    gchar *string;

    g_return_val_if_fail (E_IS_MAIL_SESSION (session), FALSE);
    g_return_val_if_fail (CAMEL_IS_MIME_MESSAGE (message), FALSE);

    medium = CAMEL_MEDIUM (message);

    header_name = "X-Evolution-Source-Folder";
    folder_uri = camel_medium_get_header (medium, header_name);

    header_name = "X-Evolution-Source-Message";
    message_uid = camel_medium_get_header (medium, header_name);

    header_name = "X-Evolution-Source-Flags";
    flag_string = camel_medium_get_header (medium, header_name);

    /* Don't report errors about missing X-Evolution-Source
     * headers.  These headers are optional, so their absence
     * is handled by doing nothing. */
    if (folder_uri == NULL || message_uid == NULL || flag_string == NULL)
        return TRUE;

    /* Convert the flag string to CamelMessageFlags. */

    string = g_strstrip (g_strdup (flag_string));
    tokens = g_strsplit (string, " ", 0);
    g_free (string);

    /* If tokens is NULL, a length of 0 will skip the loop. */
    length = (tokens != NULL) ? g_strv_length (tokens) : 0;

    for (ii = 0; ii < length; ii++) {
        /* Note: We're only checking for flags known to
         * be used in X-Evolution-Source-Flags headers.
         * Add more as needed. */
        if (g_strcmp0 (tokens[ii], "ANSWERED") == 0)
            flags |= CAMEL_MESSAGE_ANSWERED;
        else if (g_strcmp0 (tokens[ii], "ANSWERED_ALL") == 0)
            flags |= CAMEL_MESSAGE_ANSWERED_ALL;
        else if (g_strcmp0 (tokens[ii], "FORWARDED") == 0)
            flags |= CAMEL_MESSAGE_FORWARDED;
        else if (g_strcmp0 (tokens[ii], "SEEN") == 0)
            flags |= CAMEL_MESSAGE_SEEN;
        else
            g_warning (
                "Unknown flag '%s' in %s",
                tokens[ii], header_name);
    }

    g_strfreev (tokens);

    folder = e_mail_session_uri_to_folder_sync (
        session, folder_uri, 0, cancellable, error);

    if (folder == NULL)
        return FALSE;

    camel_folder_set_message_flags (
        folder, message_uid, flags, flags);

    success = camel_folder_synchronize_message_sync (
        folder, message_uid, cancellable, error);

    g_object_unref (folder);

    return success;
}

void
e_mail_session_handle_source_headers (EMailSession *session,
                                      CamelMimeMessage *message,
                                      gint io_priority,
                                      GCancellable *cancellable,
                                      GAsyncReadyCallback callback,
                                      gpointer user_data)
{
    GSimpleAsyncResult *simple;
    AsyncContext *context;

    g_return_if_fail (E_IS_MAIL_SESSION (session));
    g_return_if_fail (CAMEL_IS_MIME_MESSAGE (message));

    context = g_slice_new0 (AsyncContext);
    context->message = g_object_ref (message);

    simple = g_simple_async_result_new (
        G_OBJECT (session), callback, user_data,
        e_mail_session_handle_source_headers);

    g_simple_async_result_set_check_cancellable (simple, cancellable);

    g_simple_async_result_set_op_res_gpointer (
        simple, context, (GDestroyNotify) async_context_free);

    g_simple_async_result_run_in_thread (
        simple, (GSimpleAsyncThreadFunc)
        mail_session_handle_source_headers_thread,
        io_priority, cancellable);

    g_object_unref (simple);
}

gboolean
e_mail_session_handle_source_headers_finish (EMailSession *session,
                                             GAsyncResult *result,
                                             GError **error)
{
    GSimpleAsyncResult *simple;

    g_return_val_if_fail (
        g_simple_async_result_is_valid (
        result, G_OBJECT (session),
        e_mail_session_handle_draft_headers), FALSE);

    simple = G_SIMPLE_ASYNC_RESULT (result);

    /* Assume success unless a GError is set. */
    return !g_simple_async_result_propagate_error (simple, error);
}

static void
mail_session_send_to_thread (GSimpleAsyncResult *simple,
                             EMailSession *session,
                             GCancellable *cancellable)
{
    AsyncContext *context;
    CamelProvider *provider;
    CamelFolder *folder = NULL;
    CamelFolder *local_sent_folder;
    CamelServiceConnectionStatus status;
    GString *error_messages;
    gboolean copy_to_sent = TRUE;
    gboolean did_connect = FALSE;
    guint ii;
    GError *error = NULL;

    context = g_simple_async_result_get_op_res_gpointer (simple);

    if (camel_address_length (context->recipients) == 0)
        goto skip_send;

    /* Send the message to all recipients. */

    /* XXX Leave this untranslated in gnome-3-8.
     *     It was added during the string freeze,
     *     but should rarely ever be seen by users. */
    if (context->transport == NULL) {
        g_simple_async_result_set_error (
            simple, CAMEL_SERVICE_ERROR,
            CAMEL_SERVICE_ERROR_UNAVAILABLE,
            "No mail transport service available");
        return;
    }

    status = camel_service_get_connection_status (context->transport);
    if (status != CAMEL_SERVICE_CONNECTED) {
        did_connect = TRUE;

        camel_service_connect_sync (
            context->transport, cancellable, &error);

        if (error != NULL) {
            g_simple_async_result_take_error (simple, error);
            return;
        }
    }

    provider = camel_service_get_provider (context->transport);

    if (provider->flags & CAMEL_PROVIDER_DISABLE_SENT_FOLDER)
        copy_to_sent = FALSE;

    camel_transport_send_to_sync (
        CAMEL_TRANSPORT (context->transport),
        context->message, context->from,
        context->recipients, cancellable, &error);

    if (did_connect) {
        /* Disconnect regardless of error or cancellation,
         * but be mindful of these conditions when calling
         * camel_service_disconnect_sync(). */
        if (g_cancellable_is_cancelled (cancellable)) {
            camel_service_disconnect_sync (
                context->transport, FALSE, NULL, NULL);
        } else if (error != NULL) {
            camel_service_disconnect_sync (
                context->transport, FALSE, cancellable, NULL);
        } else {
            camel_service_disconnect_sync (
                context->transport, TRUE, cancellable, &error);
        }

        if (error != NULL) {
            g_simple_async_result_take_error (simple, error);
            return;
        }
    }

skip_send:
    /* Post the message to requested folders. */
    for (ii = 0; ii < context->post_to_uris->len; ii++) {
        CamelFolder *folder;
        const gchar *folder_uri;

        folder_uri = g_ptr_array_index (context->post_to_uris, ii);

        folder = e_mail_session_uri_to_folder_sync (
            session, folder_uri, 0, cancellable, &error);

        if (error != NULL) {
            g_warn_if_fail (folder == NULL);
            g_simple_async_result_take_error (simple, error);
            return;
        }

        g_return_if_fail (CAMEL_IS_FOLDER (folder));

        camel_folder_append_message_sync (
            folder, context->message, context->info,
            NULL, cancellable, &error);

        g_object_unref (folder);

        if (error != NULL) {
            g_simple_async_result_take_error (simple, error);
            return;
        }
    }

    /*** Post Processing ***/

    /* This accumulates error messages during post-processing. */
    error_messages = g_string_sized_new (256);

    mail_tool_restore_xevolution_headers (context->message, context->xev);

    /* Run filters on the outgoing message. */
    if (context->driver != NULL) {
        camel_filter_driver_filter_message (
            context->driver, context->message, context->info,
            NULL, NULL, NULL, "", cancellable, &error);

        if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
            goto exit;

        if (error != NULL) {
            g_string_append_printf (
                error_messages,
                _("Failed to apply outgoing filters: %s"),
                error->message);
            g_clear_error (&error);
        }

        if ((camel_message_info_flags (context->info) & CAMEL_MESSAGE_DELETED) != 0)
            copy_to_sent = FALSE;
    }

    if (!copy_to_sent)
        goto cleanup;

    /* Append the sent message to a Sent folder. */

    local_sent_folder =
        e_mail_session_get_local_folder (
        session, E_MAIL_LOCAL_FOLDER_SENT);

    folder = e_mail_session_get_fcc_for_message_sync (
        session, context->message, cancellable, &error);

    /* Sanity check. */
    g_return_if_fail (
        ((folder != NULL) && (error == NULL)) ||
        ((folder == NULL) && (error != NULL)));

    /* Append the message. */
    if (folder != NULL)
        camel_folder_append_message_sync (
            folder, context->message,
            context->info, NULL, cancellable, &error);

    if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
        goto exit;

    if (error == NULL)
        goto cleanup;

    if (folder != NULL && folder != local_sent_folder) {
        const gchar *description;

        description = camel_folder_get_description (folder);

        if (error_messages->len > 0)
            g_string_append (error_messages, "\n\n");
        g_string_append_printf (
            error_messages,
            _("Failed to append to %s: %s\n"
            "Appending to local 'Sent' folder instead."),
            description, error->message);
    }

    /* If appending to a remote Sent folder failed,
     * try appending to the local Sent folder. */
    if (folder != local_sent_folder) {

        g_clear_error (&error);

        camel_folder_append_message_sync (
            local_sent_folder, context->message,
            context->info, NULL, cancellable, &error);
    }

    if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED))
        goto exit;

    /* We can't even append to the local Sent folder?
     * In that case just leave the message in Outbox. */
    if (error != NULL) {
        if (error_messages->len > 0)
            g_string_append (error_messages, "\n\n");
        g_string_append_printf (
            error_messages,
            _("Failed to append to local 'Sent' folder: %s"),
            error->message);
        g_clear_error (&error);
        goto exit;
    }

cleanup:

    /* The send operation was successful; ignore cleanup errors. */

    /* Mark the draft message for deletion, if present. */
    e_mail_session_handle_draft_headers_sync (
        session, context->message, cancellable, &error);
    if (error != NULL) {
        g_warning ("%s", error->message);
        g_clear_error (&error);
    }

    /* Set flags on the original source message, if present.
     * Source message refers to the message being forwarded
     * or replied to. */
    e_mail_session_handle_source_headers_sync (
        session, context->message, cancellable, &error);
    if (error != NULL) {
        g_warning ("%s", error->message);
        g_clear_error (&error);
    }

exit:

    /* If we were cancelled, disregard any other errors. */
    if (g_error_matches (error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) {
        g_simple_async_result_take_error (simple, error);

    /* Stuff the accumulated error messages in a GError. */
    } else if (error_messages->len > 0) {
        g_simple_async_result_set_error (
            simple, E_MAIL_ERROR,
            E_MAIL_ERROR_POST_PROCESSING,
            "%s", error_messages->str);
    }

    /* Synchronize the Sent folder. */
    if (folder != NULL) {
        camel_folder_synchronize_sync (
            folder, FALSE, cancellable, NULL);
        g_object_unref (folder);
    }

    g_string_free (error_messages, TRUE);
}

static guint32
get_message_size (CamelMimeMessage *message,
                  GCancellable *cancellable)
{
    CamelStream *null;
    guint32 size;

    null = camel_stream_null_new ();
    camel_data_wrapper_write_to_stream_sync (
        CAMEL_DATA_WRAPPER (message), null, cancellable, NULL);
    size = CAMEL_STREAM_NULL (null)->written;
    g_object_unref (null);

    return size;
}

void
e_mail_session_send_to (EMailSession *session,
                        CamelMimeMessage *message,
                        gint io_priority,
                        GCancellable *cancellable,
                        CamelFilterGetFolderFunc get_folder_func,
                        gpointer get_folder_data,
                        GAsyncReadyCallback callback,
                        gpointer user_data)
{
    GSimpleAsyncResult *simple;
    AsyncContext *context;
    CamelAddress *from;
    CamelAddress *recipients;
    CamelMedium *medium;
    CamelMessageInfo *info;
    CamelService *transport;
    GPtrArray *post_to_uris;
    struct _camel_header_raw *xev;
    struct _camel_header_raw *header;
    const gchar *resent_from;
    GError *error = NULL;

    g_return_if_fail (E_IS_MAIL_SESSION (session));
    g_return_if_fail (CAMEL_IS_MIME_MESSAGE (message));

    medium = CAMEL_MEDIUM (message);

    camel_medium_set_header (medium, "X-Mailer", X_MAILER);

    /* Do this before removing "X-Evolution" headers. */
    transport = e_mail_session_ref_transport_for_message (
        session, message);

    xev = mail_tool_remove_xevolution_headers (message);

    /* Extract directives from X-Evolution headers. */

    post_to_uris = g_ptr_array_new ();
    for (header = xev; header != NULL; header = header->next) {
        gchar *folder_uri;

        if (g_strcmp0 (header->name, "X-Evolution-PostTo") != 0)
            continue;

        folder_uri = g_strstrip (g_strdup (header->value));
        g_ptr_array_add (post_to_uris, folder_uri);
    }

    /* Collect sender and recipients from headers. */

    from = (CamelAddress *) camel_internet_address_new ();
    recipients = (CamelAddress *) camel_internet_address_new ();
    resent_from = camel_medium_get_header (medium, "Resent-From");

    if (resent_from != NULL) {
        const CamelInternetAddress *addr;
        const gchar *type;

        camel_address_decode (from, resent_from);

        type = CAMEL_RECIPIENT_TYPE_RESENT_TO;
        addr = camel_mime_message_get_recipients (message, type);
        camel_address_cat (recipients, CAMEL_ADDRESS (addr));

        type = CAMEL_RECIPIENT_TYPE_RESENT_CC;
        addr = camel_mime_message_get_recipients (message, type);
        camel_address_cat (recipients, CAMEL_ADDRESS (addr));

        type = CAMEL_RECIPIENT_TYPE_RESENT_BCC;
        addr = camel_mime_message_get_recipients (message, type);
        camel_address_cat (recipients, CAMEL_ADDRESS (addr));

    } else {
        const CamelInternetAddress *addr;
        const gchar *type;

        addr = camel_mime_message_get_from (message);
        camel_address_copy (from, CAMEL_ADDRESS (addr));

        type = CAMEL_RECIPIENT_TYPE_TO;
        addr = camel_mime_message_get_recipients (message, type);
        camel_address_cat (recipients, CAMEL_ADDRESS (addr));

        type = CAMEL_RECIPIENT_TYPE_CC;
        addr = camel_mime_message_get_recipients (message, type);
        camel_address_cat (recipients, CAMEL_ADDRESS (addr));

        type = CAMEL_RECIPIENT_TYPE_BCC;
        addr = camel_mime_message_get_recipients (message, type);
        camel_address_cat (recipients, CAMEL_ADDRESS (addr));
    }

    /* Miscellaneous preparations. */

    info = camel_message_info_new_from_header (
        NULL, CAMEL_MIME_PART (message)->headers);
    ((CamelMessageInfoBase *) info)->size =
        get_message_size (message, cancellable);
    camel_message_info_set_flags (info, CAMEL_MESSAGE_SEEN, ~0);

    /* The rest of the processing happens in a thread. */

    context = g_slice_new0 (AsyncContext);
    context->message = g_object_ref (message);
    context->io_priority = io_priority;
    context->from = from;
    context->recipients = recipients;
    context->info = info;
    context->xev = xev;
    context->post_to_uris = post_to_uris;
    context->transport = transport;

    if (G_IS_CANCELLABLE (cancellable))
        context->cancellable = g_object_ref (cancellable);

    /* Failure here emits a runtime warning but is non-fatal. */
    context->driver = camel_session_get_filter_driver (
        CAMEL_SESSION (session), E_FILTER_SOURCE_OUTGOING, &error);
    if (context->driver != NULL && get_folder_func)
        camel_filter_driver_set_folder_func (
            context->driver, get_folder_func, get_folder_data);
    if (error != NULL) {
        g_warn_if_fail (context->driver == NULL);
        g_warning ("%s", error->message);
        g_error_free (error);
    }

    /* This gets popped in async_context_free(). */
    camel_operation_push_message (
        context->cancellable, _("Sending message"));

    simple = g_simple_async_result_new (
        G_OBJECT (session), callback,
        user_data, e_mail_session_send_to);

    g_simple_async_result_set_check_cancellable (simple, cancellable);

    g_simple_async_result_set_op_res_gpointer (
        simple, context, (GDestroyNotify) async_context_free);

    g_simple_async_result_run_in_thread (
        simple, (GSimpleAsyncThreadFunc)
        mail_session_send_to_thread,
        context->io_priority,
        context->cancellable);

    g_object_unref (simple);
}

gboolean
e_mail_session_send_to_finish (EMailSession *session,
                               GAsyncResult *result,
                               GError **error)
{
    GSimpleAsyncResult *simple;

    g_return_val_if_fail (
        g_simple_async_result_is_valid (
        result, G_OBJECT (session),
        e_mail_session_send_to), FALSE);

    simple = G_SIMPLE_ASYNC_RESULT (result);

    /* Assume success unless a GError is set. */
    return !g_simple_async_result_propagate_error (simple, error);
}

/* Helper for e_mail_session_get_fcc_for_message_sync() */
static CamelFolder *
mail_session_try_uri_to_folder (EMailSession *session,
                                const gchar *folder_uri,
                                GCancellable *cancellable,
                                GError **error)
{
    CamelFolder *folder;
    GError *local_error = NULL;

    folder = e_mail_session_uri_to_folder_sync (
        session, folder_uri, 0, cancellable, &local_error);

    /* Sanity check. */
    g_return_val_if_fail (
        ((folder != NULL) && (local_error == NULL)) ||
        ((folder == NULL) && (local_error != NULL)), NULL);

    /* Disregard specific errors. */

    /* Invalid URI. */
    if (g_error_matches (
        local_error, CAMEL_FOLDER_ERROR,
        CAMEL_FOLDER_ERROR_INVALID))
        g_clear_error (&local_error);

    /* Folder not found. */
    if (g_error_matches (
        local_error, CAMEL_STORE_ERROR,
        CAMEL_STORE_ERROR_NO_FOLDER))
        g_clear_error (&local_error);

    if (local_error != NULL)
        g_propagate_error (error, local_error);

    return folder;
}

/* Helper for e_mail_session_get_fcc_for_message_sync() */
static CamelFolder *
mail_session_ref_origin_folder (EMailSession *session,
                                CamelMimeMessage *message,
                                GCancellable *cancellable,
                                GError **error)
{
    CamelMedium *medium;
    const gchar *header_name;
    const gchar *header_value;

    medium = CAMEL_MEDIUM (message);

    /* Check that a "X-Evolution-Source-Flags" header is present
     * and its value does not contain the substring "FORWARDED". */

    header_name = "X-Evolution-Source-Flags";
    header_value = camel_medium_get_header (medium, header_name);

    if (header_value == NULL)
        return NULL;

    if (strstr (header_value, "FORWARDED") != NULL)
        return NULL;

    /* Check that a "X-Evolution-Source-Message" header is present. */

    header_name = "X-Evolution-Source-Message";
    header_value = camel_medium_get_header (medium, header_name);

    if (header_value == NULL)
        return NULL;

    /* Check that a "X-Evolution-Source-Folder" header is present.
     * Its value specifies the origin folder as a folder URI. */

    header_name = "X-Evolution-Source-Folder";
    header_value = camel_medium_get_header (medium, header_name);

    if (header_value == NULL)
        return NULL;

    /* This may return NULL without setting a GError. */
    return mail_session_try_uri_to_folder (
        session, header_value, cancellable, error);
}

/* Helper for e_mail_session_get_fcc_for_message_sync() */
static CamelFolder *
mail_session_ref_fcc_from_identity (EMailSession *session,
                                    ESource *source,
                                    CamelMimeMessage *message,
                                    GCancellable *cancellable,
                                    GError **error)
{
    ESourceRegistry *registry;
    ESourceMailSubmission *extension;
    CamelFolder *folder = NULL;
    const gchar *extension_name;
    gchar *folder_uri;

    registry = e_mail_session_get_registry (session);
    extension_name = E_SOURCE_EXTENSION_MAIL_SUBMISSION;

    if (source == NULL)
        return NULL;

    if (!e_source_registry_check_enabled (registry, source))
        return NULL;

    if (!e_source_has_extension (source, extension_name))
        return NULL;

    extension = e_source_get_extension (source, extension_name);

    if (e_source_mail_submission_get_replies_to_origin_folder (extension)) {
        GError *local_error = NULL;

        /* This may return NULL without setting a GError. */
        folder = mail_session_ref_origin_folder (
            session, message, cancellable, &local_error);

        if (local_error != NULL) {
            g_warn_if_fail (folder == NULL);
            g_propagate_error (error, local_error);
            return NULL;
        }
    }

    folder_uri = e_source_mail_submission_dup_sent_folder (extension);

    if (folder_uri != NULL && folder == NULL) {
        /* This may return NULL without setting a GError. */
        folder = mail_session_try_uri_to_folder (
            session, folder_uri, cancellable, error);
    }

    g_free (folder_uri);

    return folder;
}

/* Helper for e_mail_session_get_fcc_for_message_sync() */
static CamelFolder *
mail_session_ref_fcc_from_x_identity (EMailSession *session,
                                      CamelMimeMessage *message,
                                      GCancellable *cancellable,
                                      GError **error)
{
    ESource *source;
    ESourceRegistry *registry;
    CamelFolder *folder;
    CamelMedium *medium;
    const gchar *header_name;
    const gchar *header_value;
    gchar *uid;

    medium = CAMEL_MEDIUM (message);
    header_name = "X-Evolution-Identity";
    header_value = camel_medium_get_header (medium, header_name);

    if (header_value == NULL)
        return NULL;

    uid = g_strstrip (g_strdup (header_value));

    registry = e_mail_session_get_registry (session);
    source = e_source_registry_ref_source (registry, uid);

    /* This may return NULL without setting a GError. */
    folder = mail_session_ref_fcc_from_identity (
        session, source, message, cancellable, error);

    g_clear_object (&source);

    g_free (uid);

    return folder;
}

/* Helper for e_mail_session_get_fcc_for_message_sync() */
static CamelFolder *
mail_session_ref_fcc_from_x_fcc (EMailSession *session,
                                 CamelMimeMessage *message,
                                 GCancellable *cancellable,
                                 GError **error)
{
    CamelMedium *medium;
    const gchar *header_name;
    const gchar *header_value;

    medium = CAMEL_MEDIUM (message);
    header_name = "X-Evolution-Fcc";
    header_value = camel_medium_get_header (medium, header_name);

    if (header_value == NULL)
        return NULL;

    /* This may return NULL without setting a GError. */
    return mail_session_try_uri_to_folder (
        session, header_value, cancellable, error);
}

/* Helper for e_mail_session_get_fcc_for_message_sync() */
static CamelFolder *
mail_session_ref_fcc_from_default_identity (EMailSession *session,
                                            CamelMimeMessage *message,
                                            GCancellable *cancellable,
                                            GError **error)
{
    ESource *source;
    ESourceRegistry *registry;
    CamelFolder *folder;

    registry = e_mail_session_get_registry (session);
    source = e_source_registry_ref_default_mail_identity (registry);

    /* This may return NULL without setting a GError. */
    folder = mail_session_ref_fcc_from_identity (
        session, source, message, cancellable, error);

    g_clear_object (&source);

    return folder;
}

/**
 * e_mail_session_get_fcc_for_message_sync:
 * @session: an #EMailSession
 * @message: a #CamelMimeMessage
 * @cancellable: optional #GCancellable object, or %NULL
 * @error: return location for a #GError, or %NULL
 *
 * Obtains the preferred "carbon-copy" folder (a.k.a Fcc) for @message
 * by first checking @message for an "X-Evolution-Identity" header, and
 * then an "X-Evolution-Fcc" header.  Failing that, the function checks
 * the default mail identity (if available), and failing even that, the
 * function falls back to the Sent folder from the built-in mail store.
 *
 * Where applicable, the function attempts to honor the
 * #ESourceMailSubmission:replies-to-origin-folder preference.
 *
 * The returned #CamelFolder is referenced for thread-safety and must be
 * unreferenced with g_object_unref() when finished with it.
 *
 * If a non-recoverable error occurs, the function sets @error and returns
 * %NULL.
 *
 * Returns: a #CamelFolder, or %NULL
 **/
CamelFolder *
e_mail_session_get_fcc_for_message_sync (EMailSession *session,
                                         CamelMimeMessage *message,
                                         GCancellable *cancellable,
                                         GError **error)
{
    CamelFolder *folder = NULL;

    g_return_val_if_fail (E_IS_MAIL_SESSION (session), NULL);
    g_return_val_if_fail (CAMEL_IS_MIME_MESSAGE (message), NULL);

    /* Check for "X-Evolution-Identity" header. */
    if (folder == NULL) {
        GError *local_error = NULL;

        /* This may return NULL without setting a GError. */
        folder = mail_session_ref_fcc_from_x_identity (
            session, message, cancellable, &local_error);

        if (local_error != NULL) {
            g_warn_if_fail (folder == NULL);
            g_propagate_error (error, local_error);
            return NULL;
        }
    }

    /* Check for "X-Evolution-Fcc" header. */
    if (folder == NULL) {
        GError *local_error = NULL;

        /* This may return NULL without setting a GError. */
        folder = mail_session_ref_fcc_from_x_fcc (
            session, message, cancellable, &local_error);

        if (local_error != NULL) {
            g_warn_if_fail (folder == NULL);
            g_propagate_error (error, local_error);
            return NULL;
        }
    }

    /* Check the default mail identity. */
    if (folder == NULL) {
        GError *local_error = NULL;

        /* This may return NULL without setting a GError. */
        folder = mail_session_ref_fcc_from_default_identity (
            session, message, cancellable, &local_error);

        if (local_error != NULL) {
            g_warn_if_fail (folder == NULL);
            g_propagate_error (error, local_error);
            return NULL;
        }
    }

    /* Last resort - local Sent folder. */
    if (folder == NULL) {
        folder = e_mail_session_get_local_folder (
            session, E_MAIL_LOCAL_FOLDER_SENT);
        g_object_ref (folder);
    }

    return folder;
}

/* Helper for e_mail_session_get_fcc_for_message() */
static void
mail_session_get_fcc_for_message_thread (GSimpleAsyncResult *simple,
                                         GObject *source_object,
                                         GCancellable *cancellable)
{
    AsyncContext *async_context;
    GError *local_error = NULL;

    async_context = g_simple_async_result_get_op_res_gpointer (simple);

    async_context->folder =
        e_mail_session_get_fcc_for_message_sync (
            E_MAIL_SESSION (source_object),
            async_context->message,
            cancellable, &local_error);

    if (local_error != NULL)
        g_simple_async_result_take_error (simple, local_error);
}

/**
 * e_mail_session_get_fcc_for_message:
 * @session: an #EMailSession
 * @message: a #CamelMimeMessage
 * @io_priority: the I/O priority of the request
 * @cancellable: optional #GCancellable object, or %NULL
 * @callback: a #GAsyncReadyCallback to call when the request is satisfied
 * @user_data: data to pass to the callback function
 *
 * Asynchronously obtains the preferred "carbon-copy" folder (a.k.a Fcc) for
 * @message by first checking @message for an "X-Evolution-Identity" header,
 * and then an "X-Evolution-Fcc" header.  Failing that, the function checks
 * the default mail identity (if available), and failing even that, the
 * function falls back to the Sent folder from the built-in mail store.
 *
 * Where applicable, the function attempts to honor the
 * #ESourceMailSubmission:replies-to-origin-folder preference.
 *
 * When the operation is finished, @callback will be called.  You can then
 * call e_mail_session_get_fcc_for_message_finish() to get the result of the
 * operation.
 **/
void
e_mail_session_get_fcc_for_message (EMailSession *session,
                                    CamelMimeMessage *message,
                                    gint io_priority,
                                    GCancellable *cancellable,
                                    GAsyncReadyCallback callback,
                                    gpointer user_data)
{
    GSimpleAsyncResult *simple;
    AsyncContext *async_context;

    g_return_if_fail (E_IS_MAIL_SESSION (session));
    g_return_if_fail (CAMEL_IS_MIME_MESSAGE (message));

    async_context = g_slice_new0 (AsyncContext);
    async_context->message = g_object_ref (message);

    simple = g_simple_async_result_new (
        G_OBJECT (session), callback, user_data,
        e_mail_session_get_fcc_for_message);

    g_simple_async_result_set_check_cancellable (simple, cancellable);

    g_simple_async_result_set_op_res_gpointer (
        simple, async_context, (GDestroyNotify) async_context_free);

    g_simple_async_result_run_in_thread (
        simple, mail_session_get_fcc_for_message_thread,
        io_priority, cancellable);

    g_object_unref (simple);
}

/**
 * e_mail_session_get_fcc_for_message_finish:
 * @session: an #EMailSession
 * @result: a #GAsyncResult
 * @error: return location for a #GError, or %NULL
 *
 * Finishes the operation started with e_mail_session_get_fcc_for_message().
 *
 * The returned #CamelFolder is referenced for thread-safety and must be
 * unreferenced with g_object_unref() when finished with it.
 *
 * If a non-recoverable error occurred, the function sets @error and
 * returns %NULL.
 *
 * Returns: a #CamelFolder, or %NULL
 **/
CamelFolder *
e_mail_session_get_fcc_for_message_finish (EMailSession *session,
                                           GAsyncResult *result,
                                           GError **error)
{
    GSimpleAsyncResult *simple;
    AsyncContext *async_context;

    g_return_val_if_fail (
        g_simple_async_result_is_valid (
        result, G_OBJECT (session),
        e_mail_session_get_fcc_for_message), NULL);

    simple = G_SIMPLE_ASYNC_RESULT (result);
    async_context = g_simple_async_result_get_op_res_gpointer (simple);

    if (g_simple_async_result_propagate_error (simple, error))
        return NULL;

    g_return_val_if_fail (async_context->folder != NULL, NULL);

    return g_object_ref (async_context->folder);
}

/**
 * e_mail_session_ref_transport:
 * @session: an #EMailSession
 * @transport_uid: the UID of a mail transport
 *
 * Returns the transport #CamelService instance for @transport_uid,
 * verifying first that the @transport_uid is indeed a mail transport and
 * that the corresponding #ESource is enabled.  If these checks fail, the
 * function returns %NULL.
 *
 * The returned #CamelService is referenced for thread-safety and must be
 * unreferenced with g_object_unref() when finished with it.
 *
 * Returns: a #CamelService, or %NULL
 **/
CamelService *
e_mail_session_ref_transport (EMailSession *session,
                              const gchar *transport_uid)
{
    ESourceRegistry *registry;
    ESource *source = NULL;
    CamelService *transport = NULL;
    const gchar *extension_name;

    g_return_val_if_fail (E_IS_MAIL_SESSION (session), NULL);
    g_return_val_if_fail (transport_uid != NULL, NULL);

    registry = e_mail_session_get_registry (session);
    extension_name = E_SOURCE_EXTENSION_MAIL_TRANSPORT;

    source = e_source_registry_ref_source (registry, transport_uid);

    if (source == NULL)
        goto exit;

    if (!e_source_registry_check_enabled (registry, source))
        goto exit;

    if (!e_source_has_extension (source, extension_name))
        goto exit;

    transport = camel_session_ref_service (
        CAMEL_SESSION (session), transport_uid);

    /* Sanity check. */
    if (transport != NULL)
        g_warn_if_fail (CAMEL_IS_TRANSPORT (transport));

exit:
    g_clear_object (&source);

    return transport;
}

/* Helper for e_mail_session_ref_default_transport()
 * and mail_session_ref_transport_from_x_identity(). */
static CamelService *
mail_session_ref_transport_for_identity (EMailSession *session,
                                         ESource *source)
{
    ESourceRegistry *registry;
    ESourceMailSubmission *extension;
    CamelService *transport = NULL;
    const gchar *extension_name;
    gchar *uid;

    registry = e_mail_session_get_registry (session);
    extension_name = E_SOURCE_EXTENSION_MAIL_SUBMISSION;

    if (source == NULL)
        return NULL;

    if (!e_source_registry_check_enabled (registry, source))
        return NULL;

    if (!e_source_has_extension (source, extension_name))
        return NULL;

    extension = e_source_get_extension (source, extension_name);
    uid = e_source_mail_submission_dup_transport_uid (extension);

    if (uid != NULL) {
        transport = e_mail_session_ref_transport (session, uid);
        g_free (uid);
    }

    return transport;
}

/**
 * e_mail_session_ref_default_transport:
 * @session: an #EMailSession
 *
 * Returns the default transport #CamelService instance according to
 * #ESourceRegistry's #ESourceRegistry:default-mail-identity setting,
 * verifying first that the #ESourceMailSubmission:transport-uid named by
 * the #ESourceRegistry:default-mail-identity is indeed a mail transport,
 * and that the corresponding #ESource is enabled.  If these checks fail,
 * the function returns %NULL.
 *
 * The returned #CamelService is referenced for thread-safety and must be
 * unreferenced with g_object_unref() when finished with it.
 *
 * Returns: a #CamelService, or %NULL
 **/
CamelService *
e_mail_session_ref_default_transport (EMailSession *session)
{
    ESource *source;
    ESourceRegistry *registry;
    CamelService *transport;

    g_return_val_if_fail (E_IS_MAIL_SESSION (session), NULL);

    registry = e_mail_session_get_registry (session);
    source = e_source_registry_ref_default_mail_identity (registry);
    transport = mail_session_ref_transport_for_identity (session, source);
    g_clear_object (&source);

    return transport;
}

/* Helper for e_mail_session_ref_transport_for_message() */
static CamelService *
mail_session_ref_transport_from_x_identity (EMailSession *session,
                                            CamelMimeMessage *message)
{
    ESource *source;
    ESourceRegistry *registry;
    CamelMedium *medium;
    CamelService *transport;
    const gchar *header_name;
    const gchar *header_value;
    gchar *uid;

    medium = CAMEL_MEDIUM (message);
    header_name = "X-Evolution-Identity";
    header_value = camel_medium_get_header (medium, header_name);

    if (header_value == NULL)
        return NULL;

    uid = g_strstrip (g_strdup (header_value));

    registry = e_mail_session_get_registry (session);
    source = e_source_registry_ref_source (registry, uid);
    transport = mail_session_ref_transport_for_identity (session, source);
    g_clear_object (&source);

    g_free (uid);

    return transport;
}

/* Helper for e_mail_session_ref_transport_for_message() */
static CamelService *
mail_session_ref_transport_from_x_transport (EMailSession *session,
                                             CamelMimeMessage *message)
{
    CamelMedium *medium;
    CamelService *transport;
    const gchar *header_name;
    const gchar *header_value;
    gchar *uid;

    medium = CAMEL_MEDIUM (message);
    header_name = "X-Evolution-Transport";
    header_value = camel_medium_get_header (medium, header_name);

    if (header_value == NULL)
        return NULL;

    uid = g_strstrip (g_strdup (header_value));

    transport = e_mail_session_ref_transport (session, uid);

    g_free (uid);

    return transport;
}

/**
 * e_mail_session_ref_transport_for_message:
 * @session: an #EMailSession
 * @message: a #CamelMimeMessage
 *
 * Returns the preferred transport #CamelService instance for @message by
 * first checking @message for an "X-Evolution-Identity" header, and then
 * an "X-Evolution-Transport" header.  Failing that, the function returns
 * the default transport #CamelService instance (if available).
 *
 * The returned #CamelService is referenced for thread-safety and must be
 * unreferenced with g_object_unref() when finished with it.
 *
 * Returns: a #CamelService, or %NULL
 **/
CamelService *
e_mail_session_ref_transport_for_message (EMailSession *session,
                                          CamelMimeMessage *message)
{
    CamelService *transport = NULL;

    g_return_val_if_fail (E_IS_MAIL_SESSION (session), NULL);
    g_return_val_if_fail (CAMEL_IS_MIME_MESSAGE (message), NULL);

    /* Check for "X-Evolution-Identity" header. */
    if (transport == NULL)
        transport = mail_session_ref_transport_from_x_identity (
            session, message);

    /* Check for "X-Evolution-Transport" header. */
    if (transport == NULL)
        transport = mail_session_ref_transport_from_x_transport (
            session, message);

    /* Fall back to the default mail transport. */
    if (transport == NULL)
        transport = e_mail_session_ref_default_transport (session);

    return transport;
}