I'd like to write a service that periodically checks a POP3 account for new messages and based on custom business logic forwards the messages to an appropriate "To", and possibly changes the "From" as well. I might need to keep some messages on the server until certain conditions are ready for them to be forwarded.
I found a sample using Chilkat .NET components that might work:
http://www.example-code.com/csharp/pop3_forwarder.asp
My question is: Are there any other examples of this in the .NET space using any other components?
Thanks!
The following SO questions/answers might help finding components for the POP3 part of your porject:
Reading Email using Pop3 in C#
Free POP3 .NET library?
And you can use SmtpClient in System.Net.Mail for sending the mails:
Sending E-mail using C#
I implemented something very similar using MailBee's IMAP, POP and SMTP .NET components.
They're not free, I'm afraid, but I've found them to be pretty solid, and AfterLogic's support is fast.
There's also the free (including source code) LumiSoft Mail Server, that has POP3 relay support to collect messages from a POP3 server and manage them from there, you could adapt that? (It's written in C#, is nice to work with and upgrades cleanly to VS2008). I've had no problems with that either.
Try Mail.dll .NET email component. It has SSL support, POP3 and SMTP clients.
using(Pop3 pop3 = new Pop3())
{
pop3.Connect("mail.host.com"); // Connect to the server
pop3.Login("user", "password");
foreach(string uid in pop3.GetAll())
{
// Receive mail
IMail mail = new MailBuilder()
.CreateFromEml(pop3.GetMessageByUID(uid));
Console.WriteLine(mail.Subject);
}
pop3.Close(true);
}
You can download it here
Related
I am trying to send a standard email message through AWS WorkMail using the SmtpClient in .NET Core. The configuration is very standard according to Amazon Documentation:
https://docs.amazonaws.cn/en_us/general/latest/gr/workmail.html
"Smtp": {
"MailServer": "smtp.mail.eu-west-1.awsapps.com",
"MailPort": "465",
"SenderName": "Us us us",
"FromAddress": "email#domain.com",
"Username": "email#domain.com",
"Password": "Password1$",
"EnableSsl": "true"
},
The settings are injected and the SmtpClient gets properly instantiated and the sending of the email is just:
var mail = new MailMessage
{
From = new MailAddress(_smtpSettings.FromAddress, _smtpSettings.SenderName),
SubjectEncoding = Encoding.UTF8,
BodyEncoding = Encoding.UTF8,
IsBodyHtml = true,
Body = message,
Subject = subject,
Priority = MailPriority.High
};
mail.To.Add(new MailAddress(sendToEmail));
_smtpClient.Send(mail);
Sadly, the sending always fails with a gateway timeout. We tried switching for 587 for STARTTLS and providing the Username without the domain (#). The server sending has proper SSL certificate installed and the mailserver is exactly the one we have our smtp on. Although this would not be a relevant solution, I also increased the timeout to 10 seconds (even though this would not be a solution).
Any idea what could be wrong? I am tearing my hair already. Seems to be an issue with AWS WorkMail.
Just adding to the existing comment. SMTPClient is actually obsolete/deprecated but is not being marked as so. See comments here (https://github.com/dotnet/dotnet-api-docs/issues/2986#issuecomment-430805681)
Essentially it boils down to SmtpClient hasn't been updated in years and is missing many features. The .NET Core team wanted to mark it as obsolete, but some developers have existing projects with "Warnings as Errors" turned on. It would instantly make any project that is using SmtpClient with Warnings as Errors turned on suddenly stop building. So... It's kinda deprecated, but not being marked so in some official docs.
MailKit is actually being pushed by Microsoft full stop for people to use when it comes to Email. Much to some developers chargrin who don't want to use a third party library for such a "simple" and common feature. Just in my personal experience, I think Mailkit is great and super easy to use. A quick guide to getting up and running is here : https://dotnetcoretutorials.com/2017/11/02/using-mailkit-send-receive-email-asp-net-core/
So the problem is that the default .NET Core SmtpClient does not support StartSSL (implicit SSL) which is the only accepted option by WorkMail. You see, WorkMail allows only connections that start from SSL and the SmtpClient first starts from unencrypted and then switches over to encrypted if it cannot connect.
If you are trying this, you will not get this to work using standard SmtpClient and as usually the case with Microsoft, they don't recognize it as an issue. You can either try tunneling or better just use one of the available libraries. Sadly, most of them are paid, there is AIM but it doesn't work with .NET Core and I didn't want to spend time porting not my own library to .NET Standard so I ended up using Mailkit.
There are some issues with the library though, first, before sending you have to call Connect which takes host and port as parameter, that means you cannot just inject premade smtpclient as singleton and have to instantiate it within the place of usage. That's dope and no interface also makes it unmockable which might blow your integration tests. Moreover, you have to do an ugly line before calling send like so:
emailClient.AuthenticationMechanisms.Remove("XOAUTH2");
But at least it works.
We are thinking about moving to O365; however, we developed software that uses our current Exchange server to send email both to external users as well as to a support box when errors occur.
I've been testing this to ensure that the code we have in place will continue to work with O365 but so far, I have not been very successful.
I have tried using .Net's SmtpClient as well as MailKit's SmtpClient and neither one seems to work. I keep getting error (this is the error from MailKit -- the .Net error is similar)
"AuthenticationInvalidCredentials: 5.7.3 Authentication unsuccessful [*.prod.exchangelabs.com]"
I can use the credentials that I have in my code to log into OWA -- so I know the credentials are valid. Is it not possible to send email via O356? Is there any special configuration that has to happen in Exchange to make this possible?
Here is what I've tried so far:
MailKit
var msg = new MimeMessage();
msg.From.Add(new MailboxAddress("Support","support#mydomain.com"));
msg.To.Add(new MailboxAddress("Me","me#mydomain.com"));
msg.To.Add(new MailboxAddress("External User","euser#externaldomain.com"));
msg.Subject = "Test";
msg.Body = new TextPart("plain"){
Text = "Here is a message for you"
};
using(var client = new SmtpClient()){
client.ServerCertificateValidationCallback = (s,c,h,e) => true;
client.AuthenticationMechanisms.Remove("XOAUTH2"); //Not sure what this does. Have tried with and without
client.Connect("smtp.office365.com", 587, MailKit.Security.SecureSocketOptions.StartTls);
client.Authenticate(new NetworkCredential("support#mydomain.com", "supportPwd"));
client.Send(msg);
client.Disconnect(true);
}
The .Net SmtpClient code looked very similar to the MailKit code.
Is there a way to send through O365 with a licensed user? (code above)
Are there any special settings required in Exchange or on the licensed user to make this work? (If the answer to 1 is yes)
Is it possible to send email through a shared mailbox for which the credentialed user has Send As rights?
Update
I'm still getting the same error message. We do have MFA enabled for our domain users. However, we have a policy that does not require MFA for users when they are signing in from a trusted location (our org's IP). I also listed our IP as a Trusted IP. In my mind, MFA shouldn't be the issue here.
I know the credentials are correct. I copied them from the code and pasted them in to the login screen when signing into M365 -- and I got in just fine.
What am I doing wrong?
Yes, you can.
Usersettings:
Server-settings :
https://support.office.com/en-us/article/POP-IMAP-and-SMTP-settings-for-Outlook-com-d088b986-291d-42b8-9564-9c414e2aa040
SMTP server name smtp.office365.com
SMTP port 587
SMTP encryption method STARTTLS
No, you cannot. You need a licenced user to send mail via SMTP.
https://answers.microsoft.com/en-us/msoffice/forum/msoffice_o365admin/set-up-smtp-relay-with-shared-mailbox/d7b98214-9564-432c-b098-525a98c529fb
A customer of ours has a newsletter system set up with TYPO3 and we had to create a new mailbox for this. However, a light one will suffice: instead of a Office 365 Business Premium we only assigned a Office 365 F1 licence.
Edit: also found this: Can Office365 shared mailbox use SMTP?
For anyone who is having similar issues, I found that my problem was a Conditional Access Policy. Microsoft provides a Baseline Policy: Block Legacy Authentication -- which had been turned on in our AAD.
In looking at the Policy, it is designed to BLOCK any authentication mechanisms that don't require MFA. This includes things like POP and SMTP. Once I disabled this policy, the code listed above worked just fine.
For me only disabling "Security defaults" helped.
I'm trying to find some code that will allow me to suck out every email in my Gmail account, it seems that the code currently out there using Atom reader only reads unread messages.
I want to read everything, subjects, body and attachments.
Is it possible, does anyone have some working code.
Dave
What you have want to do is not a simple application that we can help you out to write a mail client application, It needs a lots of effort to read many articles about how POP3 or IMAP mail clients work also you have to understand RFC 1939 and RFC 1081 documents related to these protocols. Anyway You have to use IMAP or POP3 protocols to implement you mail client application there are many articles outside which you can refer to them.
SMTP and POP3 Mail Server
A POP3 Client in C# .NET
And RFC Documents :
Post Office Protocol
You can do this via e.g. IMAP. It should be enabled at the account settings though.
There are numerous C# tutorials about using/implementing IMAP, just google for them.
Your best bet, as others have noted, is using the IMAP protocol. Note, however, that the Google IMAP implementation requires a secure connection, so it is not just a matter of implementing IMAP.
There is a C# implementation here, which also includes the secure connection stuff, but beware that there are quite a few bugs in it, concerning things like header-encoding and others, so be prepared to fix a few bugs if you decide to use it.
Learn how to read information from XML and you can get every information you want on Gmail from this feed https://mail.google.com/mail/feed/atom. I have one sample code below which reads the number of unread messages and reads the title and summary, but you can get another information like from who, attachments, ect. No extra libraries needed :)
try
{
System.Net.WebClient objClient = new System.Net.WebClient();
string response;
string title;
string summary;
//Creating a new xml document
XmlDocument doc = new XmlDocument();
//Logging in Gmail server to get data
objClient.Credentials = new System.Net.NetworkCredential("Email", "Password");
//reading data and converting to string
response = Encoding.UTF8.GetString(objClient.DownloadData(#"https://mail.google.com/mail/feed/atom"));
response = response.Replace(#"<feed version=""0.3"" xmlns=""http://purl.org/atom/ns#"">", #"<feed>");
//loading into an XML so we can get information easily
doc.LoadXml(response);
//nr of emails
nr = doc.SelectSingleNode(#"/feed/fullcount").InnerText;
//Reading the title and the summary for every email
foreach (XmlNode node in doc.SelectNodes(#"/feed/entry"))
{
title = node.SelectSingleNode("title").InnerText;
summary = node.SelectSingleNode("summary").InnerText;
}
}
}
catch (Exception exe)
{
MessageBox.Show("Check your network connection");
}
I've been following this site with a lot of admiration especially on how questions are professionally answered so I decided to be fully involved.
Please, I need urgent help on a project that I have been working on for a long time but it's almost stalled now just because of a critical issue.
An aspect of the program automates email sending to clients using the free email server systems. Due to the high frequency of email sending, I observed that the email server we're sending to drops larger parts of the emails sent out and literally blocks delivery of major emails to the recipients.
I have tried to reduce the rate of sending email out but to no avail. My fear now is my IP address might have been blocked or may be blocked soon if this continue. The program is not spamming but have to be developed in order to contact a large database of recipients at a goal within short time - like about 1000 or more recipients.
I am using Webbrowser control in C# to automate the process of logging in to the mail server and sending the email out.
Now, what I want is a sample code to use publicly available web proxy servers for each email sent out such that the source IP address appears dynamic and different to the target email server each time a message is sent out to it.
I mean, I want to dynamically get and use free public proxy servers with the Webbrowser control to send out the emails. In this way I believe the email servers would not be able to reject the emails base on the IP address source. I want to know how to dynamically get literally one web proxy server for each email sent, if possible each time.
This project is very critical and this feature is a determinant. I have googled endlessly without any straight forward solution to this issue. I would, therefore, appreciate any useful help, sample codes or resources that could help me to solve this nagging problem once and for all.
Thank you!
Your problem is "free email server systems": they consider you a spammer, and the idea you suggest (spoofing IPs) will, if detected, ruin your reputation.
If you explain what you are trying to accomplish, perhaps someone here can offer a better design.
Are you trying to give people with free email accounts (like Hotmail) bulk-emailing capabilities?
First of all (if I understood your answer right), you don't have to use WebBrowser control - you can use specified .NET solutions that allows you to efficiently sending mails:
MailMessage msg = new MailMessage("from", "to", "subject", "body text");
SmtpClient client = new SmtpClient("smtp server");
System.Net.NetworkCredential cred = new System.Net.NetworkCredential("user", "password");
client.UseDefaultCredentials = false;
client.Credentials = cred;
Client.Send(msg);
Unfortunately, if you want to send e-mails to many recipients and you want to be sure, that these messages reach the recipients - you have to do it using your own e-mail server or do it by purchase the service on a paid e-mail servers - then they will not treat you as a spammer.
But if you anyway want to send e-mails by rotation proxy servers or similar sollution - you can define your proxy:
SmtpClient client = new SmtpClient("my.proxy_server.com", 8080);
First you have to collect any list of available proxy servers which allows you to do it in reasonable time (servers switching can significantly increase total process time because conection time can be different for each proxy server)
Proxy servers list ordered by access time:
http://www.publicproxyservers.com/proxy/list_avr_time1.html
Using the OpenPOP .net client for getting messages from Gmail.
I'm wondering how I can get only the new messages?
Currently, I get the atom feed and then get as many emails as the feed has with the OpenPOP client (starting from the first).
GmailAtomFeed feed = new GmailAtomFeed("user", "pass");
feed.GetFeed();
int unread = feed.FeedEntries.Count;
POPClient client = new POPClient("pop.gmail.com", 995, "user", "pass", AuthenticationMethod.USERPASS, true);
for (int i = 0; i < unread; i++)
{
Message m = client.GetMessage(i, false);
// ...
}
Is there a better way to do this?
And how do I set the unread messages to be read?
I doubt you can do it with pop3. From my understanding POP3 doesn't support the notion of the unread\unseen email. It should be up to the client to track messages which were already shown to the user and which were not.
What you can do is switch to using IMAP protocol to access gmail. Check this link for how you can switch it on for your gmail account Getting started with IMAP for Gmail.
Now, if you're using c# there are some commercial libraries for IMAP and there free\opensource ones: like this one on codeproject: IMAP Client library using C#. What you have to do to get unseen messages is to specify "unseen" flag for the select command. Here's an example
You have to store the UIDL of each email in a local database. When you want to check for new mail, you retrieve the UIDLs on the server and see if you have if already in your local database; if not, it's a new mail.
Outlook uses the same strategy.
same Q How to retrieve only new emails using POP3 protocol