ATTENTION: You are viewing a page formatted for mobile devices; to view the full web page, click HERE.

Other Software > Developer's Corner

Check Gmail using C#

<< < (2/8) > >>

wraith808:
If you click the plain text link, it will convert it to plain text.

As for a code sample:


--- Code: C# ---using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.IO;using UtilsLib; namespace MyFTP{    public class Downloader        {                private bool DownloadFile()                {                        var ftpMyFile = new UtilsLib.SimpleFTP                        {                            LocalFilePath = "C:\",                            LocalFileName = "localFile.jpg",                            URI = "mysite.com",                            UserId = "myName",                            Password = "myPass",                            RemoteFileName = "myfile.jpg",                            UseBinaryMode = true                        };                         bool ftpResult = ftpMyFile.InitiateTransfer(OnFTPProgress, OnFTPStart, OnFTPFinish);                        return ftpResult;                }                 public void OnFTPFinish(bool ftpSuccessful, string message)                {                        if (!(ftpSuccessful))                        {                                // Do whatever you want if the ftp is unsuccessful                        }                        else                        {                                // Do whatever you want if the ftp is successful                        }                }                 public void OnFTPStart(string message)                {                        // for reporting of progress - called when the FTP starts                }                 public void OnFTPProgress(int bytesTransferred, string message)                {                        // do whatever updating of progress that you want to do                }        }}

kyrathaba:
Awesome, Wraith!  Thanks!!

I'll share my own cool discovery:


I run a roleplaying game on www.myth-weavers.com at http://www.myth-weavers.com/forumdisplay.php?f=11199

I've been developing an application for my players that will allow them to create a new character and submit it to me, their Game Master, as an email attachment, for my perusal and approval.  In thinking ahead to the Game Master application I'll be creating at some point, one of the functions I want it to have is that it automatically checks my Gmail account when the application starts, to see if any players have emailed me any character files.

Well, I've experimented until I found a way to do this.

The following brief code snippet is simply proof of concept.  It uses the free ImapX DLL.  In my example below, I set a Subject Line to look for that signals my program I've found the right email (in this case "myflag").  Then, it looks through my Gmail emails until it finds such an email, and downloads the email itself as a *.eml file, and saves the first attachment to the same directory.

This snippet is very crude, but could be refined to download all attachments (if there are more than one).  I could build in error-checking to ensure there IS an attachment before trying to save it to file, etc.


--- ---            ImapX.ImapClient client = new ImapX.ImapClient("imap.gmail.com", 993, true);
            bool result = client.Connection();
            if (result) {
                result = client.LogIn("[email protected]", "myPassword");
                if (result) {
                    ImapX.FolderCollection folders = client.Folders;
                    foreach (ImapX.Message m in client.Folders["INBOX"].Messages)
            {
              m.Process();                   
                      if (m.Subject == "myflag") {
                          string path = Application.StartupPath + "\\email\\";
                          string filename = "myEmail";
                          m.SaveAsEmlToFile(path, filename);
                          m.Attachments[0].SaveFile(path);
                      }
            }
                }
            }
            else {
                MessageBox.Show("connection failed");
            }

kyrathaba:
Improved code-listing:

Snipplr code snippet


--- Code: C# ---/* Required for this example:             *              * a C# WinForms application             * add reference to ImapX.dll available here:             * http://hellowebapps.com/wp-content/uploads/2010/07/ImapX_1.2.3.126.zip             * http://dl.dropbox.com/u/12124382/ImapX.zip             * a button <button1>             * a textbox <textBox1>             *              * Notes: I used a very specific Subject line as my search criteria, but you need not do this.  You could             * just as easily have your code search through and download each and every email and/or every email's attachments.             */              ImapX.ImapClient client = new ImapX.ImapClient("imap.gmail.com", 993, true);            bool result = client.Connection();            if (result) {                result = client.LogIn("[email protected]", "mypassword");                if (result) {                    textBox1.AppendText(Environment.NewLine + Environment.NewLine + "Log-on successful" +                        Environment.NewLine + Environment.NewLine);                    ImapX.FolderCollection folders = client.Folders;                    foreach (ImapX.Message m in client.Folders["INBOX"].Messages)                        {                          m.Process();                       if (m.Subject == "test email with 3 attachments (txt, png, wav)") {                          textBox1.AppendText(Environment.NewLine + Environment.NewLine + "Found email in question..." +                              Environment.NewLine + Environment.NewLine);                          string path = Application.StartupPath + "\\email\\";                          string filename = "TxtPngWav";                          //comment-out following line if you don't want to d/l the actual email                          m.SaveAsEmlToFile(path, filename);                          //use above line, and comment out the following if(){}, if you prefer to download the whole                           //email in .eml format                          if (m.Attachments.Count > 0) {                              for (int i = 0; i < m.Attachments.Count; i++) {                                  m.Attachments[i].SaveFile(path);                                  textBox1.AppendText("Saved attachment #" + (i + 1).ToString());                                  textBox1.AppendText(Environment.NewLine + Environment.NewLine);                              }                          }                                                }                        }                }            }            else {                textBox1.AppendText("connection failed");            }

mouser:
nice.

kyrathaba:
And since I've shown how to check Gmail using C# and Gmail's IMAP, the following snippet shows how to send an email programmatically, through your Gmail account, using C# and Gmail's SMTP.  Please note that, although the code doesn't require notification to the user that an email is about to be sent, you should always notify the end-user of your program, and give him/her the option of whether or not to send the email.  If you don't, their firewall or protective software may scare them when it pops up a message about your program attempting to send email.

Notes:

(1) your namespace's using section should include the following:
using System.Net.Mail;

(2) my example code places the email-sending code in a Button's Click() event-handler


--- Code: C# ---private void button1_Click(object sender, EventArgs e) {            DialogResult dr = MessageBox.Show("Send email?", "Get Permission", MessageBoxButtons.YesNo, MessageBoxIcon.Question,                MessageBoxDefaultButton.Button2);             if (dr == DialogResult.Yes) {                 SmtpClient smtpClnt = new SmtpClient("smtp.gmail.com", 587);                 try {                     MailMessage oMail = new MailMessage();                    oMail.To.Add(new MailAddress("[email protected]"));                    oMail.From = new MailAddress("[email protected]");                    oMail.IsBodyHtml = true;                                        oMail.Body = "your message body goes here";                    oMail.Subject = "your subject goes here";                     smtpClnt.Timeout = 100000;                     smtpClnt.EnableSsl = true;                    System.Net.NetworkCredential nc = new System.Net.NetworkCredential("[email protected]", "your_password");                    smtpClnt.Credentials = nc;                     Attachment oAttached = new Attachment("C:\\yourimage.jpg");                    oMail.Attachments.Add(oAttached);                     smtpClnt.SendCompleted += new SendCompletedEventHandler(MailDeliveryComplete);                     smtpClnt.SendAsync(oMail, "sending");                 }                catch (Exception mailExc) {                    if (mailExc.ToString().IndexOf("could not be resolved") >= 0) {                        int line = mailExc.ToString().IndexOf("line");                        int leng = mailExc.ToString().Length;                        string sLin = mailExc.ToString().Substring(line, (leng - line));                        string s = "Either the developer's Gmail SMTP was unavailable, or else your computer is not currently ";                        s += "connected to the internet.  Error generated at source code " + sLin;                        MessageBox.Show(s, "Unable to send character file via email");                    }                    else {                        MessageBox.Show("Error:" + Environment.NewLine + Environment.NewLine +                            mailExc.Message + Environment.NewLine + Environment.NewLine + mailExc.ToString());                    }                }                finally {                     //don't invoke smtpClnt.Dispose() here; if you do, the mail never sends                }                         }        }           private void MailDeliveryComplete(object sender, System.ComponentModel.AsyncCompletedEventArgs e) {             string myMessage = e.ToString();            string myCaption = string.Empty;             if (e.Error != null) {                myCaption = "Error sending email";            }            else if (e.Cancelled) {                myCaption = "Sending of email cancelled.";            }            else {                myCaption = "Your email message was sent successfully to the Game Master.";            }             MessageBox.Show(myMessage, myCaption);         }

Navigation

[0] Message Index

[#] Next page

[*] Previous page

Go to full version