Office365 Imap not working programatically - c#

Trying to connect to imap using MailKit library. While this code works for Gmail and hot mail.
It gives Login Failed error for Office 365.
using (var client = new ImapClient(new ProtocolLogger("imap.log")))
{
client.Timeout = 120000;
client.Connect("outlook.office365.com",
93,SecureSocketOptions.SslOnConnect);
client.Authenticate("xxxxx#xxxxinet.com", "XXXXXPassword");
client.Inbox.Open(FolderAccess.ReadOnly);
var uids = client.Inbox.Search(SearchQuery.All);
foreach (var uid in uids)
{
var message = client.Inbox.GetMessage(uid);
// write the message to a file
message.WriteTo(string.Format("{0}.eml", uid));
}
client.Disconnect(true);
}

Microsoft has Deprecated basic authentication starting from 2023. You can read more about it on their article Deprecation of Basic authentication in Exchange Online
You need to use Oauth2 authentication Authenticate an IMAP, POP or SMTP connection using OAuth

Related

Office 365 - MailKit hitting spam folders c#

I am trying to use MailKit for sending email via office 365 for a web app that I am currently developing.
I have had various issues in the past with office 365 and sending emails and this evening I have stumbled across multiple articles and stack questions addressing office 365 and sending via smtp and MailKit being the preferred option.
I am using this code
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Simon Price", "simon.price#xxxx.co.uk"));
message.To.Add(new MailboxAddress("Recipient Nasme", "emailAddress"));
message.Subject = "Still hitting spam";
message.Body = new TextPart("html")
{
Text = #"sample test"
};
using (var client = new SmtpClient())
{
client.Connect("smtp.office365.com", 587, SecureSocketOptions.Auto);
// Note: only needed if the SMTP server requires authentication
client.Authenticate("simon.price#sxxx.co.uk", "xxxx");
client.Send(message);
client.Disconnect(true);
}
Which does send the email, however, it continually hits the spam folders of each recipient. I very much suspect this is me missing a configuration, however I cannot see where I am going wrong in this and would appreciate some help.
Resources I have looked at include but not exhausted (i may have missed some)
https://github.com/jstedfast/MailKit
https://dotnetcoretutorials.com/2017/11/02/using-mailkit-send-receive-email-asp-net-core/
Does Office 365 have a preferred way of sending attachments when using MailKit?
Authenticating to Office 365 Outlook IMAP using MailKit fails for a specific user
https://unop.uk/sending-email-in-.net-core-with-office-365-and-mailkit/

Using Mailkit : "The SMTP server has unexpectedly disconnected."

I am trying to use a free SMTP relay from SendGrid to send emails from my ASP.NET application. I can connect to the server, but when I try to authenticate, I get this error : "The SMTP server has unexpectedly disconnected."
using (var client = new SmtpClient())
{
client.ServerCertificateValidationCallback =
(sender, certificate, certChainType, errors) => true;
client.AuthenticationMechanisms.Remove("XOAUTH2");
// connection
client.Connect("smtp.host", 465, true);
client.Authenticate("UserName", "Password");//error occurs here
client.Send(email);
client.Disconnect(true);
}
Once again, I can connect without any problem, but when I try to authenticate, I get the previously mentionned error...
Any suggestions?
Cheers
You have to supply:
Username: is apikey (as a hard-coded value 'apikey').
Password: is the apikey you generated from the web, which is a big hashy-like string.
You can find this on their docs. But it was hard to find.
I solved my issue changing from SendGrid to gooogle's free SMTP service for all of their users. Simply follow the steps here
and you should be good to go!

Azure Function: Client was not authenticated to send anonymous mail during MAIL FROM [DB6P189CA0021.EURP189.PROD.OUTLOOK.COM]

I want to send email in Azure Function. I write down below code. It works properly in console app & I am able to send email using the credentials. But when I tested the same code in Azure Function it throws me below error.
Exception while executing function: Functions.HttpTriggerCSharp. Microsoft.Azure.WebJobs.Script: One or more errors occurred. f-HttpTriggerCSharp__-1774598883: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM [DB6P189CA0021.EURP189.PROD.OUTLOOK.COM]
The code I used -
SmtpClient client = new SmtpClient("smtp-mail.outlook.com");
string _sender = "--email--";
string _password = "-password---";
client.Port = 587;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
System.Net.NetworkCredential credentials =
new System.Net.NetworkCredential(_sender, _password);
client.EnableSsl = true;
client.Credentials = credentials;
string recipient = "--test#outlook.com--";
string subject="Temperature of device exceeds";
string message="Temperature of device exceeds";
try
{
var mail = new MailMessage(_sender.Trim(), recipient.Trim());
mail.Subject = subject;
mail.Body = message;
client.Send(mail);
}
catch (Exception ex)
{
}
I use a queuetrigger and follow your code in my azure function(v1) and it works well.
The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM
This message indicates that the SMTP server configured in your Outgoing Mail Account is connecting to an SMTP client submission endpoint which cannot be used for direct send.
Configure your Exchange SMTP to direct send.
Configure the email notification In the DS-Client > setup > configuration > notification Selected SMTP, add the SMTP server settings and selected add the SMTP server settings
Server require authentication.
Add the office365 authenticated account information in the SMTP server authentication window.
Refer to the following Microsoft articles for more information:
Fix issues with printers, scanners, and LOB applications that send email using Office 365
How to set up a multifunction device or application to send email using Office 365

Email not sending in azure web app

I have configured my application in Azure web apps. I am sending the mail using smtp server. The outlook is sending emails properly. Other mail providers like(Gmail) are not sending emails. Please help.
Other mail providers like(Gmail) are not sending emails
You could check the providers that have policy to allow to do that.
Take gmail for example, as Ankit Kumar mentioned that you need to turn Allow less secure apps: on for your gmail account.
I also test it on my side, it works correctly. The following is my demo code.
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Tom Gmail", "xx#gmail.com"));
message.To.Add(new MailboxAddress("Tom Hotmail", "xxx#hotmail.com"));
message.Subject = "I am a mail subject";
message.Body = new TextPart("plain")
{
Text = "I am a mail body."
};
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
client.Authenticate("sunguiguan#gmail.com", "#WSX3edc");
client.Send(message);
client.Disconnect(true);
}
We also could use SendGrid on the Azure,more detail please refer to How to Send Email Using SendGrid with Azure.

How can I get the unread/new messages from Gmail using POP3?

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

Categories

Resources