Reputation: 13272
I was following this link here: https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.mailmessage?view=net-8.0&redirectedfrom=MSDN
I have done something similar in the past but I am now using Office 365 where everything is just hosted online. Is there something else that needs to be setup for SMTP to work? I just see the code spin and spin and it never progresses, never sends, just spins forever and tells me nothing.
using System.Collections;
using System.Net.Mail;
using System.Net.Mime;
using System.Net;
string server = "smtp.office365.com";
var user = "user";
var password = "password";
var from = "[email protected]";
var to = "[email protected]";
var subject = "CSharp sent message";
var body = "Sent from code that is being made by Mail Message";
var message = new MailMessage(from, to, subject, body);
var client = new SmtpClient(server);
//client.Credentials = CredentialCache.DefaultNetworkCredentials;
new NetworkCredential(user, password, "domain.com");
//client.Port = 465; //465 or 587
try
{
//NOTE: Neither this or below line will work. They both just spin.
//await client.SendMailAsync(from, to, subject, body);
client.Send(message);
client.SendCompleted += (o, s) =>
{
o.ToString();
var obj = s;
obj.ToString();
};
Console.WriteLine("Sent");
}
catch (Exception ex)
{
_ = ex;
}
Picture for clarity. I can step over line 24 and it doesn't fail, doesn't get to the next line. Just doesn't do anything.
Upvotes: 0
Views: 203
Reputation: 13272
So the answer is to change a few lines to:
var client = new SmtpClient(server, 587);
client.EnableSsl = true;
client.Credentials = new NetworkCredential(user, password);
It appears 465 won't work and still just spins and spins -\ 0 /-. I don't know, I don't work for MS. Given it says not to keep using this method for new code I'm just using this temporarily for a small thing and then would recommend to anyone reading this to looking into mailkit
Upvotes: 0