Writing C# code to send an email with office 365 - c#

This seems like it should be simple to me, but I cannot get it to work. I can easily send emails with code like this:
[OperationBehavior(Impersonation = ImpersonationOption.Required)]
public static void sendEmail(string toEmail, string toName, string subject, string body)
{
MailAddress from = new MailAddress("TizzyFoe#MyCompany.com", "Mr Tizzy Foe");
const string UserName = "TizzyFoe#MyCompanyInc.com";
const string password = "ThisIsMyRealPassword";
const string host = "smtp.office365.com";
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress(toEmail, toName));
msg.From = from;
msg.Subject = subject;
msg.Body = body;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = true;
//client.Credentials = (System.Net.ICredentialsByHost)System.Net.CredentialCache.DefaultCredentials;
//client.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
client.Credentials = new System.Net.NetworkCredential(UserName, password);
client.Port = 587;
client.Host = host;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
client.Send(msg);
}
But putting my password into code like that is bad for a variety of obvious reasons.
So what I want to do is say, okay this program is running on my laptop and I am logged in as me. So shouldn't the program be able to access my credentials. And you can see i commented out two failed attempts to do just that:
//client.Credentials = (System.Net.ICredentialsByHost)System.Net.CredentialCache.DefaultCredentials;
//client.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
both of those result in this exception:
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
Maybe my program can only access some encrypted version of my credentials which cannot be passed to the office365 server? I have kind of a working knowledge of security concepts, but this is getting over my head.
I feel like this can't possible be that difficult. I know there are applications which can send automated emails through office 365. Right now, I'm just testing my code as a console app, but my thinking was ultimately I'd create a windows service to run it. Maybe the windows service would be able to pass credentials?

Related

Error sending email via SMTP in C#, Does this still work in 2017?

Having researched the issue extensively especially applying recommendations from similar issues on stackoverflow, the below code still returns error ""System.Net.Mail.SmtpException: Syntax error, command unrecognized. The server response was: connection rejected at....""
try
{
var mail = new MailMessage();
mail.From = new MailAddress("demo77377#gmail.com");
mail.To.Add(new MailAddress("xxxxxxx#gmail.com"));
mail.Subject = "TEST";
mail.Body = "This is a test mail from C# program";
using (var smtp = new SmtpClient())
{
smtp.Credentials = new System.Net.NetworkCredential("demo77377#gmail.com", "AABBCCDDEE1!","gmail.com");
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Timeout = 10000;
//
smtp.Send(mail);
Console.WriteLine("Message sent successfully");
Console.ReadLine();
}
}
catch (Exception e)
I have done everything possible
On Client> I have alternated smtp properties (permutation) etc
On Server> I have made gmail account less secure, I have disabled captcha etc
I observed that similar issues on stackoverflow were mostly dated over 3years ago and thus, is it possible that gmail no longer supports this SMTP method via C#, likewise has it been deprecated in favor of gmail API
Also, please find provided in code, original password supplied for the gmail account, in order to confirm if this issue is general or isolated to this gmail account
Thanks
This code is verified to work fine:
var fromAddress = new MailAddress("YOUREMAIL#gmail.com", "YOUREMAIL#gmail.com");
var toAddress = new MailAddress("YOUREMAIL#gmail.com", "YOUREMAIL#gmail.com");
const string fromPassword = "YOURPASSWORD";
const string subject = "YOUREMAIL#gmail.com";
const string body = "YOUREMAIL#gmail.com";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword),
Timeout = 20000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
I'm not comfortable including your personal details even though you have so I have removed them. Obviously replace the email and password with the correct details.
Finally got it working after switching from my hotel's wireless network to office network...type of network connection has a role to play in sending email via SMTP in C#

send an email using SMTP without password in C#

I have a web application using ASP.net and C#,in one step it will need
from the user to
send an email to someone with an attachments.
my problem is when the user will send the email i don't want to put their
password every time the user send.
i want to send an email without the password of the sender.
any way to do that using SMTP ?
and this is a sample of my code "not all".
the code is worked correctly when i put my password , but without it ,it
is not work, i need a way to send emails without put the password but
in the same time using smtp protocol.
private void button1_Click(object sender, EventArgs e)
{
string smtpAddress = "smtp.office365.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "my email";
string password = "******";
string emailTo = "receiver mail";
string subject = "Hello";
string body = "Hello, I'm just writing this to say Hi!";
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
// Can set to false, if you are sending pure text.
// mail.Attachments.Add(new Attachment("C:\\SomeFile.txt"));
// mail.Attachments.Add(new Attachment("C:\\SomeZip.zip"));
using (SmtpClient smtp = new SmtpClient(smtpAddress,portNumber))
{
smtp.UseDefaultCredentials = true;
smtp.Credentials = new NetworkCredential(emailFrom, password);
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
MessageBox.Show("message sent");
}
}
I believe this can be accomplished easily, but with some restrictions.
Have a look at the MSDN article on configuring SMTP in your config file.
If your SMTP server allows it, your email object's from address may not need to be the same as the credentials used to connect to the SMTP server.
So, set the from address of your email object as you already are:
mail.From = new MailAddress(emailFrom);
But, configure your smtp connection one of two ways:
Set your app to run under an account that has permission to access the SMTP server
Include credentials for the SMTP server in your config, like this.
Then, just do something like this:
using (SmtpClient smtp = new SmtpClient())
{
smtp.Send(mail);
}
Let the configuration file handle setting up SMTP for you. This is also great because you don't need to change any of your code if you switch servers.
Just remember to be careful with any sensitive settings in your config file! (AKA, don't check them into a public github repo)

Programmatic emails triggering "The server response was: 5.7.1 Unable to relay"

When I use outlook, I am able to send test email to my gmail address, however, when I do it from a console application it triggers : "The server response was: 5.7.1 Unable to relay"
using System.Net.Mail;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
MailMessage mail = new MailMessage("xxx#myCompany.com", "xxx#gmail.com");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "xxx.xxx.com";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);
}
}
}
I verified that i have the correct client host through outlook. I also sent a test email to myself (from xx#mycompany to xx#mycompany) and that worked (although it sent it to the junk box). Why will it not let me send outgoing emails through this console app, but I can through the same address in outlook.
I'm pretty sure that if you have client.UseDefaultCredentials = false;, you need to set the credentials. At least that is what I do:
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(someusername, somepassword);
edit: I should clarify, client.UseDefaultCredentials = false;, does not necessarily mean you need credentials listed, but if you are trying to send to an external domain (gmail.com), then your SMTP server will most likely require some type of SMTP Auth.

Hmailserver C# SMTP

I'm just trying to get my hmailserver to send mail from my C# program. The part that's killing me is the SSL part.
I originally got this error: The SMTP server requires a secure connection or the client was not authenticated. The server response was: SMTP authentication is required.
So I added: smtp.EnableSsl = true; and now I get Server does not support secure connections.
Here is my code, this is driving me nuts. Do I have to create my own SSL or is there a way to disable SSL on hmailserver side?
MailMessage mail = new MailMessage("jlnt#ademo.net", "com", "NEW Item", emailBody);
SmtpClient smtp = new SmtpClient("1.1.1.250");
smtp.Port = 25;
NetworkCredential login = new NetworkCredential("ja#test.net", "dg");
smtp.Credentials = login;
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Send(mail);
Ahh okay what you have to do is in HMailServer go to advanced- ip ranges. Create a new IP range for example if you 192.168.1.2, you have to make the range 192.168.1.1-192.168.1.3, then at bottom uncheck all the required smtp authentication boxes.
Annoying...
To enable secure connection to send email throught your email provider, you have to change the port number.
MailMessage mail = new MailMessage("jlnt#ademo.net", "com", "NEW Item", emailBody);
SmtpClient smtp = new SmtpClient("1.1.1.250");
//smtp.Port =25;
smtp.Port =587;
NetworkCredential login = new NetworkCredential("ja#test.net", "dg");
smtp.Credentials = login;
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Send(mail);
i was having this issue, what i did was used localhost ip and EnableSsl to false
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = "127.0.0.1";
smtpClient.Credentials = new NetworkCredential("test#123test.com", "pass123");
smtpClient.EnableSsl = false;
// then your other statements like: from, to, body, to send mail
this guide will help you setup custom NetworkCredentials in HMailServer as used above, hope helps someone.
I have stumbled on this question when trying to configure hMailServer to work to e-mail sending from C#. I have tried the following:
C# SmtpClient - does not work with implicit SSL - see this question and answers
AegisImplicitMail from here - could not make it work with UTF-8 strings (I have diacritics in my strings)
MailKit from here - very powerful and mature, no problems using it
I aimed for the following:
decent security
being able to send e-mails to mainstream e-mail providers (e.g. Google, Yahoo) and reach Inbox
being able to receive e-mails from mainstream e-mail providers
C# code
public void MailKitSend(string senderEmail, string senderName, string subject, string bodyText, string receivers, string receiversCc)
{
// no receivers, no e-mail is sent
if (string.IsNullOrEmpty(receivers))
return;
var msg = new MimeMessage();
msg.From.Add(new MailboxAddress(Encoding.UTF8, senderName, senderEmail));
msg.Subject = subject;
var bb = new BodyBuilder {HtmlBody = bodyText};
msg.Body = bb.ToMessageBody();
IList<string> receiversEmails = receivers.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
foreach (string receiver in receiversEmails)
msg.To.Add(new MailboxAddress(Encoding.UTF8, "", receiver));
if (!string.IsNullOrEmpty(receiversCc))
{
IList<string> receiversEmailsCc = receiversCc.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();
foreach (string receiverCc in receiversEmailsCc)
msg.Cc.Add(new MailboxAddress(Encoding.UTF8, "", receiverCc));
}
try
{
var sc = new MailKit.Net.Smtp.SmtpClient();
if (!string.IsNullOrWhiteSpace(SmtpUser) && !string.IsNullOrWhiteSpace(SmtpPassword))
{
sc.Connect(SmtpServer, 465);
sc.Authenticate(SmtpUser, SmtpPassword);
}
sc.Send(msg);
sc.Disconnect(true);
}
catch (Exception exc)
{
string err = $"Error sending e-mail from {senderEmail} ({senderName}) to {receivers}: {exc}";
throw new ApplicationException(err);
}
}
hMailServer configuration
1) Opened ports - 25, 143, 465, 995 are opened to ensure that you can send and receive e-mail
2) TCP/IP ports configuration
SMTP / 0.0.0.0 / port 25 / no security (allow receiving start process)
SMTP / 0.0.0.0 / port 465 / SSL/TLS security (must define a SSL certificate)
POP3 / 0.0.0.0 / port 995 / SSL/TLS security (use the same SSL certificate)
3) pre C# testing
Run Diagnostics from hMailServer Administrator
Use an e-mail client that allows manual configuration of various settings such as ports for each protocol, security. I have used Thunderbird. Include sending of e-mails to external providers and receiving e-mails from them (I have tried with Gmail).
I made no changes in IP ranges and left the implicit ones (My computer and the Internet).
Although it's 7 years passed since the accepted answer was posted - I also upvoted it in the beginning - I want to emphasize that the suggested solution disables the whole authentication process which is unnecessary. The problem is the line with :
smtp.UseDefaultCredentials = false;
Just remove that line and it should work.
I post here the working solution for me (note that I'm not using SSL):
MailMessage mail = new MailMessage("a1#test.com", "foooo#gmail.com");
SmtpClient client = new SmtpClient();
client.Credentials = new NetworkCredential("a1#test.com", "test");
client.Port = 25;
client.EnableSsl = false;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "...IPv4 Address from ipconfig...";
mail.Subject = "this is a test email.";
mail.Body = "this is my test email body";
client.Send(mail);

CDO Email Configuration

I'm attempting to send email using CDO. I'm wanting to change the settings to always send from a specific smtp server with a specific user, pass, and from. However, when I attempt to change the config, I get an error that the data is readonly. How do you go about changing the config of the message?
Message msg = new Message();
IConfiguration config = msg.Configuration;
config.Fields["smtpserver"] = "SERVER";
msg.Subject = "TEST";
msg.From = "FROM#FROM.com";
msg.To = "TO#TO.com";
msg.TextBody = "TESTING";
msg.Send();
I've attempted using System.Net.Mail, but that seems to be firewall blocked. I get the exception message Unable to connect to the remote server : No connection could be made because the target machine actively refused it {IP}:67
MailMessage msg = new MailMessage();
msg.Subject = "TESTING";
msg.From = new MailAddress("MYMAIL#MYMAIL.org");
msg.To.Add(new System.Net.Mail.MailAddress("TOMAIL#TOMAIL.org"));
msg.Body = "dubbly doo";
SmtpClient client = new SmtpClient();
client.Host = "HOST";
client.Port = 67;
client.EnableSsl = true;
client.Credentials = new NetworkCredential("USERNAME", "PASSWORD", "DOMAIN");
client.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
client.Send(msg);
}
catch(SmtpException e)
{
Console.Write(e.InnerException.Message+":"+e.InnerException.InnerException.Message);
Console.ReadLine();
}
Is using CDO a requirement? You are already using C#, so I recommend porting your CDO code to System.Net.Mail.
http://msdn.microsoft.com/en-us/library/dk1fb84h.aspx
Edit:
Since it sounds in the comments like you are having configuration issues with System.Net.Mail, I would use some of the SysInternals tools (specifically TcpView) to monitor your connections as you step through the CDO code. That way you can see what IP and ports your code is using to connect.
Then armed with that information, you should be able to configure your System.Net.Mail code with the correct settings.

Categories

Resources