?
Solved

Perform email operations by C# code

Posted on 2014-04-21
18
Medium Priority
?
1,629 Views
Last Modified: 2014-04-24
Hello Experts,

I want to know how to check my emails if I have received any NEW email with particular subject and I want to do some operations like reading body content & its subject and send a reply email to the user and also to attach a file to reply email.

And I want to achieve this by C# code.

Any URL's or sample demo code which help me in understanding will be helpful.

Thank You !!
0
Comment
Question by:Md Shah
17 Comments
 
LVL 71

Assisted Solution

by:Éric Moreau
Éric Moreau earned 400 total points
ID: 40013177
there is nothing built-in the .Net framework to read emails. I suggest that you try http://www.limilabs.com/mail (commercial product) or http://sourceforge.net/projects/hpop/ (free product)
0
 
LVL 7

Assisted Solution

by:Utkarsh Kulkarni
Utkarsh Kulkarni earned 1600 total points
ID: 40014117
Hi,
You can use OpenPop.NET for this as Eric suggested.
A sample code will go like this

var client = new POPClient();
client.Connect("pop.gmail.com", 995, true);
client.Authenticate("<Email Address Goes Here", "Your Password Goes Here");

var count = client.GetMessageCount();
Message message = client.GetMessage(count);
string subject = message.Headers.Subject;

Open in new window


You can play with code & check with subject & retrieve the body.
0
 
LVL 6

Expert Comment

by:Brijesh Gandhi
ID: 40014437
Try following

Solution 1

Solution 2
0
What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

 
LVL 8

Author Comment

by:Md Shah
ID: 40014908
Thanks Eric and astroutkarsh for your response.

Based on your replies I have created a sample console application just to check If I could able to read messages correctly.

First time the Message Count is showing correctly and if I run the app once again its being reduced by one number every time and finally the message count is coming to zero. Even though i have not deleted any of the messages from my account.

Please find the attached snapshots which will give you more info.

I might be missing something somewhere which is causing it to reduce the message count. I have tried by adding client.Disconnect(); at the last but it didn't worked.

Please let me know where I may be wrongly coded.

Cheers..
Actual-email-account-snapshot.JPG
0
 
LVL 8

Author Comment

by:Md Shah
ID: 40014918
Thanks Eric and astroutkarsh for your response.

Based on your replies I have created a sample console application just to check If I could able to read messages correctly.

First time the Message Count is showing correctly and if I run the app once again its being reduced by one number every time and finally the message count is coming to zero. Even though i have not deleted any of the messages from my account.

Please find the attached snapshots which will give you more info.

I might be missing something somewhere which is causing it to reduce the message count. I have tried by adding client.Disconnect(); at the last but it didn't worked.

Please let me know where I may be wrongly coded.

Cheers..
Actual-email-account-snapshot.JPG
demo-working-code.JPG
first-iteration.jpg
first-output.JPG
second-iteration.jpg
second-output.JPG
0
 
LVL 7

Expert Comment

by:Utkarsh Kulkarni
ID: 40014919
Hi,

Can you put code block here? (Take out username & password).
I did not had this issue when I tested this.

If required I can place my code block here.

-------------------xxx-------------------------
I missed your post with details.
0
 
LVL 7

Accepted Solution

by:
Utkarsh Kulkarni earned 1600 total points
ID: 40014944
Here is my piece of code, i tried in web application though

using OpenPop.Common.Logging;
using OpenPop.Mime;
using OpenPop.Mime.Decode;
using OpenPop.Mime.Header;
using OpenPop.Pop3;

public partial class EmailTesting : System.Web.UI.Page
    {
protected void Page_Load(object sender, EventArgs e)
        {
            List<Message> lstMsgs = new List<Message>();
            lstMsgs = FetchAllMessages("pop.gmail.com", 995, true,"xxxxxxxxx@gmail.com","xxxxxxx");
            Label _o;
            string _bodymsg = string.Empty;           
            if (lstMsgs.Count > 0)
            {
                foreach (Message _msg in lstMsgs)
                {
                   
                        _o = new Label();
                        _bodymsg = _msg.Headers.Subject + "--- Body ---";
                        if (_msg.MessagePart.Body  != null  )
                        {
                            _bodymsg += _msg.MessagePart.GetBodyAsText();
                        }
                        else
                        {
                            _bodymsg += "Empty";
                        }
                        

                        _o.Text = _bodymsg + "<br/>";
                        _o.ForeColor = System.Drawing.Color.Black;
                        pnlMsgs.Controls.Add(_o);
                    
                }

            }
            else
            {
                _o = new Label();
                _o.Text = "<b>No Email message found.</b>";
                _o.ForeColor = System.Drawing.Color.Red;
                pnlMsgs.Controls.Add(_o);
            }
        }

        public List<Message> FetchAllMessages(string hostname, int port, bool useSsl, string username, string password)
        {
            // The client disconnects from the server when being disposed
            using (Pop3Client client = new Pop3Client())
            {
                // Connect to the server
                client.Connect(hostname, port, useSsl);

                // Authenticate ourselves towards the server
                client.Authenticate(username, password);

                // Get the number of messages in the inbox
                int messageCount = client.GetMessageCount();

                // We want to download all messages
                List<Message> allMessages = new List<Message>(messageCount);

                // Messages are numbered in the interval: [1, messageCount]
                // Ergo: message numbers are 1-based.
                // Most servers give the latest message the highest number
                for (int i = messageCount; i > 0; i--)
                {
                    allMessages.Add(client.GetMessage(i));
                }

                // Now return the fetched messages
                return allMessages;
            }
        }
}

Open in new window

<body>
    <form id="form1" runat="server">
    <div>    
        <asp:Panel runat="server" ID="pnlMsgs">

        </asp:Panel>
    </div>
    </form>
</body>

Open in new window

0
 
LVL 8

Author Comment

by:Md Shah
ID: 40015071
Thanks Utkarsh Kulkarni for placing your working code.

I see that their's not much difference between yours and mine.

During your development, have you not faced my situation like message count being reduced on repeated checks.

Now I m bit curious why mine is not working here :(
0
 
LVL 7

Expert Comment

by:Utkarsh Kulkarni
ID: 40015110
What setting you have applied for this account on GMail ?
Keep on server / Read / Unread etc?
0
 
LVL 8

Author Comment

by:Md Shah
ID: 40015352
Pardon Me.. I am not getting what you are asking about settings in GMAIL account.

I have created a new GMAIL account today morning solely for this purpose.

Could you guide me where & how i can get to that settings you are talking about ?

Cheers...
0
 
LVL 7

Expert Comment

by:Utkarsh Kulkarni
ID: 40015652
I was referring to attached pic.
You can access this with action on top right corner (below a/c details) in gmail.
Gmail-settings.jpg
0
 
LVL 8

Author Comment

by:Md Shah
ID: 40015725
This is is what i see out there...

Check attachment...

Cheers..
Capture.PNG
0
 
LVL 8

Author Comment

by:Md Shah
ID: 40016608
Guys,

I have attached a recording in drive...

https://drive.google.com/file/d/0BzRwprydrSL-NkppVDJpWTdrZTg/edit?usp=sharing

Have a look at it, if you can get a better idea on the issue I am facing...

Once an email is read by POP then its not being identified next time :(
0
 
LVL 7

Assisted Solution

by:Utkarsh Kulkarni
Utkarsh Kulkarni earned 1600 total points
ID: 40020156
Hi,

In Pop Download, choose option 1 ( Enable for All mails).

and check then.
0
 
LVL 8

Author Comment

by:Md Shah
ID: 40020248
Wonderful. That has done the trick..

Thanks Expert...!!
0
 
LVL 8

Author Closing Comment

by:Md Shah
ID: 40020260
Thanks Experts for your time...
0
 
LVL 17

Expert Comment

by:BudDurland
ID: 40021642
0

Featured Post

What Kind of Coding Program is Right for You?

There are many ways to learn to code these days. From coding bootcamps like Flatiron School to online courses to totally free beginner resources. The best way to learn to code depends on many factors, but the most important one is you. See what course is best for you.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

An ASP.NET Web Form User Control is not newly introduced in ASP.NET. In fact, it was an old technology yet still playing a role to generate web content, especially when we want to use it to have a better and easy way to control part of the web conte…
Article by: Shaun
Tiling windows is a great way to see multiple applications at once. Windows Tiler is a tool that automatically tiles open application windows as the open and close.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …
This video tutorial shows you the steps to go through to set up what I believe to be the best email app on the android platform to read Exchange mail.  Get the app on your phone: The first step is to make sure you have the Samsung Email app on your …

569 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question