0 votes

Hi all
I'm wondering if there is a way to hide, handle the exception I get when running my "Reply to an email" project. I'm using it to reply with a wifi token when a mail is sent to certain email address. See the code below (may not be the prettiest one yet) :

public partial class Form1 : Form
{
    public Form1()
    {

        InitializeComponent();

        Timer MyTimer = new Timer();
        MyTimer.Interval = (1 * 15 * 1000); // 30 secs
        MyTimer.Tick += new EventHandler(MyTimer_Tick);
        MyTimer.Start();

    }

    private void MyTimer_Tick(object sender, EventArgs e)
    {
        mailVoucher();
    }

    private void mailVoucher() //Mail virkni
    {
        IMail original = GetFirstMessage();

        ReplyBuilder replyBuilder = original.Reply();

        replyBuilder.HtmlReplyTemplate = @"
        <html>
        <head>
            <title>[Subject]</title>
        </head>
        <body>
        [Html]
        </body>
        </html>";

        replyBuilder.SubjectReplyTemplate = "Gestapassi";

        //Retreive-ar voucherinn
        string voucher = getVoucher();

        replyBuilder.Html = "Lykilorð á OM_GUEST er : " + voucher;

        MailBuilder builder = replyBuilder.Reply(
            new MailBox("xxxxxx", "xxxxxx"));

        IMail reply = builder.Create();

        using (Smtp smtp = new Smtp())
        {
            smtp.ConnectSSL("outlook.office365.com");
            smtp.UseBestLogin("xxxxx@xxxx", "xxxxxxxx");
            smtp.SendMessage(reply);
            smtp.Close();
        }
    }

    private IMail GetFirstMessage() 
    {
        IMail email;
        using (Imap imap = new Imap())
        {
            imap.ConnectSSL("outlook.office365.com");
            imap.UseBestLogin("xxxxx@xxxx", "xxxxxx");
            imap.SelectInbox();

            List<long> uids = imap.Search(Flag.Unseen);

            if (uids.Count == 0)
                throw new Exception("There are no messages");

            var eml = imap.GetMessageByUID(uids[0]);
            email = new MailBuilder().CreateFromEml(eml);                   
            imap.Close();
        }
        return email; 
    }
}

I'm running this on a server and keep getting the exception box on-screen. When I ignore it (don't click quit/continue) the program stills runs as expected.

Best regards
Steini Ben

by

1 Answer

0 votes
 
Best answer

Your GetFirstMessage() method throws an exception when there are no unread messages in your INBOX.

Consider returning null in such case:

if (uids.Count == 0)
{
    email = null;
}
else
{
     var eml = imap.GetMessageByUID(uids[0]);
     email = new MailBuilder().CreateFromEml(eml);                   
}
imap.Close();

...and handle such response in mailVoucher() method

IMail original = GetFirstMessage();
if (original == null)
    return;
by (301k points)
...