SDK Script remote-mail.are

remote-mail.are
/* DESC: This script reads and sends mails from a remote IMAP/POP3/SMTP server
 * Copyright (C) 2014 NetModule AG, Switzerland
 */
 
SERVER = "mail.example.com";
IMAPURL = strcat("imap://", SERVER);
SMTPURL = strcat("smtp://", SERVER);
USR = "user";
PWD = "password";
KEEP = 1;
AUTORESPOND = 0;
RESPONDTO = "test@example.com";
 
 
cnt = nb_mail_list(USR, PWD, IMAPURL);
if (cnt < 0) {
    printf("ERROR: unable to list mail on %s\n", SERVER);
    exit(1);
}
 
printf("saw %d mails on %s\n\n", cnt, SERVER);
 
for (i = 0; i < cnt; i++) {
    mail = nb_mail_fetch(USR, PWD, IMAPURL, i);
    if (!mail) {
        printf("ERROR: unable to retrieve mail #%d\n", i);
        continue;
    } 
 
    /* dump mail */
    printf("--- mail #%d ---\n", i);
    printf("From: %s\n", struct_get(mail, "from"));
    printf("To: %s\n", struct_get(mail, "to"));
    printf("Subject: %s\n", struct_get(mail, "subject"));
    printf("Date: %s\n", struct_get(mail, "date"));
    printf("\n%s\n---\n", struct_get(mail, "body"));
 
 
    if (AUTORESPOND) {
        /* auto-respond to sender */
        m = strstr(struct_get(mail, "from"), RESPONDTO);
        if (!is_void(m)) {
            printf("sending response to '%s'\n", struct_get(mail, "from"));
 
            response = mkstruct("from", struct_get(mail, "to"),
                                "to", struct_get(mail, "from"),
                                "subject", strcat("Re: ", struct_get(mail, "subject")),
                                "body", "got your mail");
 
            if (nb_mail_send(USR, PWD, SMTPURL, response) != 0) {
                printf("ERROR: unable to send response for mail #%d\n", i);
            } else {
                printf("responded to mail #%d\n");
            }
        }
    }
}
 
if (!KEEP) {
    for (i = (cnt-1); i >= 0; i--) {
        if (nb_mail_delete(USR, PWD, IMAPURL, i) != 0) {
            printf("ERROR: unable to delete mail #%d\n", i);
        } else {
            printf("deleted mail #%d\n", i);
        }
    }
}
 
exit(0);