Sending an E-Mail via Google Mail - c#

I'm trying to send an E-Mail via Gmail using MailKit. This is my code:
using MailKit.Net.Smtp;
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587, false);
//...
}
But no matter what I try I always get the following exception:
System.IO.IOException: The authentication or decryption has failed.
I already tried to enable "unsafe apps" in my Google account, but that did not help. So far I could not find any working example that shows how to send mail via Gmail.
Edit:
I just tried running the Code on WIndows (using .NET), and it worked perfectly. The E-Mail got sent right away. Only when I run it on Linux/OSX using Mono, it does not work.

I just found the answer!
Adding the following line of code to the beginning of my program solved it:
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
(o, certificate, chain, errors) => true;
Now MailKit sends the E-Mails as it should. So does the .NET/Mono SMTP class.

Related

SMTP c# MailKit smtp.Authenticate fails

I am trying to send an e-mail using c# MailKit SMTP (code below).
It connects successfully (with Connect method) and then it fails on Authenticate method call with an error " Username and Password not accepted.". I know the user name and password are correct. I also tried "mail.optusnet.com.au" server on port 25 - same story.
What is wrong with my call to smtp.Connect method. I have spent whole day experimenting and got nowhere. Can somebody help please.
// send email
using var smtp = new SmtpClient();
smtp.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
smtp.Authenticate("rejkid#gmail.com", "Password1");
smtp.Send(email);
smtp.Disconnect(true);
Google no longer allows your password to be used when authenticating via SMTP, POP3 or IMAP.
You either need to use OAuth2 or you need to enable 2FA on your Google account and then generate an app-specific password and use that.

Does Mailkit supports sending anonymous emails?

The Exchange host that I am trying to send emails from does not require authentication. In the past I have successfully achieved this using SmtpClient Class, but as Microsoft is recommending Mailkit, I prefer going for this one.
Does Mailkit always require a username and a password to connect? I have been searching for an answer everywhere but I cannot seem to find one.
This is my code so far:
private void Send(MimeMessage message)
{
using (var client = new SmtpClient(new ProtocolLogger(Console.OpenStandardOutput())))
{
client.Connect(Host, Port, SecureSocketOptions.None);
client.Send(message);
client.Disconnect(true);
}
}
And of course I am getting an error: 5.7.1 client was not authenticated
Thank you loads.
Does Mailkit always require a username and a password to connect? I have been searching for an answer everywhere but I cannot seem to find one.
MailKit does not require authentication - that's up to the server to require it or not.
If a server doesn't require authentication, your code just needs to not call client.Authenticate() (or AuthenticateAsync if you are using async code) just like you attempted to do in your example code snippet.
5.7.1 client was not authenticated is an error that came from your SMTP server when you attempted to send a message and suggests that your SMTP server is configured to require authentication.
None of the exception messages that MailKit throws start with an error code string (5.7.1 is an SMTP error code), so if an exception is thrown starting with an SMTP error code string, then it means it came from the server.

Can I send SMTP email through Office365 shared mailbox?

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.

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!

What could cause a message sent from Gmail SMTP using C# not to arrive - No exception is thrown

I am trying to send mail through my Google Apps email account. This is setup on my own domain and is all working fine through the web interface and through outlook.
However, i'm trying to send an email from a webpage using C#, I get no exceptions and everything appears to go smoothly, but the emails never seem to arrive:
MailMessage msg = new MailMessage("no-reply#xxxx.co.uk", "dan#xxxx.co.uk");
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential("no-reply#xxxx.co.uk", "xxxxxxxxx");
smtp.EnableSsl = true;
msg.IsBodyHtml = true;
msg.Body = body;
smtp.Send(msg);
The body is a string which i've generated earlier in the code. As far as i'm aware, if there was a problem with actually connecting to the SMTP server at Gmail then I would get an exception thrown.
Any ideas what could cause this not to work? Only thing different I can see compared to other peoples examples is that I have set body as HTML and i'm sending from a Google Apps account rather than an #gmail.com account.
The google apps itself is all configured fully and working, i've set this up numerous times so I know it's not likely to be a problem there.
I also tried sending on port 25, as that's what you use when configuring Outlook to send from a Gmail account.
Same result for both, no exception thrown, but email never arrives. Both emails the sender and receiver are on my domain using Google Apps for Gmail.
EDIT:
Also I should mention that I have signed in using both accounts, and both have IMAP and POP enabled in their settings etc.
New findings
This is a strange one
If I send mail manually from:
no-reply#mydomain.com to dan#mydomain.com - Then it works
But if I send it through code this way...it doesn't work...
If I send the following through code it does work:
no-reply#mydomain.com to me#gmail.com or me#ntlworld.com - This works through code!
I would then be led to think that this means a problem with dan#mydomain.com receiving messages...But it receives any messages sent manually from any google, hotmail, or ntlworld email address i've tried.
So either Google Apps accounts can't receive email sent through code (unlikely) or something else is at play here
The server may silently discard your message if there is a problem with it.
- Despite any spec saying otherwise.
The message might be lost in the ether despite being "delivered".
The SMTP server may be applying severe filtering and might additionally require that your sender and destination email addresses match up 'correctly'
I suggest trying with a different SMTP host just to check. :)
When you setup Google Apps, even if the MX records are all working correctly for sending mail manually to/from other accounts, there can still be problems.
The answer is to wait 12-24 hours after setting up your MX Records, even if everything else is working fine.
If you receive no exception, then to me this is the only answer at the moment.
All is working correctly now. Even though all MX records were correct on my DNS and email appeared to be working, there were still changes going on in the background

Categories

Resources