Solved

Perform email operations by C# code

Posted on 2014-04-21
18
1,262 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
18 Comments
 
LVL 69

Assisted Solution

by:Éric Moreau
Éric Moreau earned 100 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 400 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
 
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 400 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
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
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 400 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

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

This story has been written with permission from the scammed victim, a valued client of mine – identity protected by request.
Find out what Office 365 Transport Rules are, how they work and their limitations managing Office 365 signatures.
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 explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.

743 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now