Sending mail with MimeKit and default email - c#

I need send a mail from my program. Then I use MimeKit.
The problem is when run the program in another computer, with another email configurated by default.
So I need to use that default email on that computer.
My code is
var message = new MimeMessage();
message.From.Add(new MailboxAddress("CCCC", "cccc#xxxxx.com"));
message.To.Add(new MailboxAddress("KKKK", "kkkkkk#jjjjj.es"));
message.Subject = "¿Cómo estás?";
message.Body = new TextPart("plano")
{
Text = #"Kaixo Lorea"
};
using (var smtpClient = new SmtpClient())
{
smtpClient.Send(message);
}
I'm working with C# and Windows 10
Thanks

As far as I understand your question, you are asking how to read the SMTP server configuration settings from whatever email client program is configured on another system.
I doubt you'll have much luck with that.

Related

Trying to send a mail from a .NET 5 console application using SMTP

Context
I'm developing an application using WPF and .NET 5 for a research institute. The client would like to receive an email when something goes wrong during an experience because it can last several days.
Before adding this feature to the software, I made a simple test program to send an email from a console application and it worked... mostly.
Disclaimer : I know there are tons of threads about this subject, and I have read nearly a hundred. The code itself doesn't seem to be the problem and I did setup the google account with two factor authentication (I also tried the "Less secure app" option).
The problem
I said the problem doesn't seem to be the code because I actually managed to send emails that way, using my personal gmail address. Problem is, I don't want to use my own address to send mail to the client... So I created an new gmail address and enabled 2FA. And when I try to send an email with the new address I get this in the emitter inbox :
What I already tried
I've tried various recipient and port with the same result. I've looked for this issue on google support, on forums and on youtube but I didn't find anything similar to my problem. I even waited 2 weeks to make sure it wasn't because the address was too recent and judged as "untrustworthy" or something like that.
The code I used
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
MailAddress to = new MailAddress("recipient#gmail.com");
MailAddress from = new MailAddress("emitter#gmail.com");
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the new SMTP client.";
message.Body = "Using this new feature, you can send an e-mail message from an application very easily.";
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
SmtpClient client = new SmtpClient
{
EnableSsl = true,
Port = 587,
Host = "smtp.gmail.com",
Timeout = 10000,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("emitter#gmail.com", "app-specific-password")
};
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in Main(): {0}",
ex.ToString());
}
message.Dispose();
}
What I would like
I just need to be able to send a few emails per day, to one or two contacts, from a WPF application. Nothing fancy. It seems that the two options I got are :
to find how to create a neutral email address that can use gmail smtp
or
to find another (easy and free) solution to send emails.
Can you help me with that, please ?

C# SMTP sends email with empty body in productive enviroment

I'm working on a project that needs to send an invitation email to an email specified by the user.
I'm using C#, SMTP and the body is an html template.
If I try, Locally there is no problem, I can send emails and everything works as intended, I receive the email with the correct template.
The problem comes when I'm trying to send the email from the productive environment, from there the email received is with the empty body and no traces of the body template.
This is the code I'm using to send the email.
MailMessage msg = new MailMessage(Configuration["EmailFrom"],to);
msg.Subject = subject;
msg.Body = this.emailBody;
msg.IsBodyHtml = true;
msg.BodyEncoding = System.Text.Encoding.UTF8;
SmtpClient smtpClient = new SmtpClient(Configuration["SMTP"], Convert.ToInt32(Configuration["PORT"]));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(Configuration["EmailFrom"], Configuration["PasswordEmailFrom"]);
smtpClient.Credentials = credentials;
smtpClient.EnableSsl = true;
smtpClient.Send(msg);
Now, I know the productive enviroment is hosted in a AWS server, but don't know the configuration of the server or if it has something to do with the problem.
The templates are using divs instead of tables in some cases but i think is an unrelated issue, so I really don't know where the problem could be.
Edit:
I grab the info i will use to replace from the database and grabbing the template from a local HTML file hosted in the server.
This is the code where it sets the email template and replace the content:
EmailService sendDriverInvitation = new EmailService(_env);
sendDriverInvitation.setEmailTemplate($"ClientApp/{AssetsDirectory}/assets/emailTemplates/InvitationDriver.html");
sendDriverInvitation.emailBody = sendDriverInvitation.emailBody.Replace("[DER Name]", userName).Replace("[Company Name]", DbaName);
sendDriverInvitation.sendMail(email, "Invitation Email");
And this is the code for setEmailTemplate:
HTMLReader reader = new HTMLReader();
string htmlCompleteTemplatePath = Path.Combine(webRoot, htmlTemplatePath);
this.emailBody = reader.ReadHtmlFile(htmlCompleteTemplatePath);

Can't send email using implicit SSL smtp server

I wrote up a sample program by copying the code in this KB article with some little edit as far as user's info. It uses the deprecate .NET library System.Web.Mail to do it because the new System.Net.Mail does not support implicit SSL. I went and tested it with Google smtp server on port 465 which is their implicit email port and everything works. However, when I gave this to a client to test it at his network, nothing get sent/receive, here is the error:
2013-03-07 15:33:43 - The transport failed to connect to the server.
2013-03-07 15:33:43 - at System.Web.Mail.SmtpMail.LateBoundAccessHelper.CallMethod(Object obj, String methodName, Object[] args)
2013-03-07 15:33:43 - at System.Web.Mail.SmtpMail.CdoSysHelper.Send(MailMessage message)
2013-03-07 15:33:43 - at System.Web.Mail.SmtpMail.Send(MailMessage message)
I'm not very well versed when it comes to email SSL so here is my possible theory to the root cause:
Assume he is using the right smtp server and right port (SSL port), I wonder if if any of the following could be the cause:
They are using SSL on the mail server and yet he does not have the certificate installed on the machine where he runs my program from even though he is on the same domain and use the same email domain as a sender.
They are using SSL but they maybe using NTLM or Anonymous authentication while my program uses basic authentication.
Sorry if I provide little information because I myself is quite foreign in this area so I'm still researching more.
Do you know of any steps I can do at my end to ensure my little test program can send using the smtp server of an implicit SSL email server?
Edit: I did add the following line in my code to indicates I'm using SSL.
oMsg.Fields.Add("http://schemas.microsoft.com/cdo/configuration/smtpusessl", "true");
Maybe this is to late to answer but have a look on https://sourceforge.net/p/netimplicitssl/wiki/Home/
You can send mail to port 465
Without the need of modifying your code, that much.
From the wiki page of project :
var mailMessage = new MimeMailMessage();
mailMessage.Subject = "test mail";
mailMessage.Body = "hi dude!";
mailMessage.Sender = new MimeMailAddress("you#gmail.com", "your name");
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MimeMailAddress("yourfriend#gmail.com", "your friendd's name"));
mailMessage.Attachments.Add(new MimeAttachment("your file address"));
var emailer = new SmtpSocketClient();
emailer.Host = "your mail server address";
emailer.Port = 465;
emailer.EnableSsl = true;
emailer.User = "mail sever user name";
emailer.Password = "mail sever password" ;
emailer.AuthenticationMode = AuthenticationType.PlainText;
emailer.MailMessage = mailMessage;
emailer.OnMailSent += new SendCompletedEventHandler(OnMailSent);
//Send email
emailer.SendMessageAsync();
// A simple call back function:
private void OnMailSent(object sender, AsyncCompletedEventArgs asynccompletedeventargs)
{
Console.Out.WriteLine(asynccompletedeventargs.UserState.ToString());
}
Here I am using gmail smtp to send mail using c#. See the code below. It will give you an insight, How the stuffs are working. Replace gmail settings with your email server settings. Dont worry about the security certificates, they will be taken care of by the framework itself.
public static bool SendMail(string to, string subject, string body)
{
bool result;
try
{
var mailMessage = new MailMessage
{
From = new MailAddress("your email address")
};
mailMessage.To.Add(new MailAddress(to));
mailMessage.IsBodyHtml = true;
mailMessage.Subject = subject;
mailMessage.Body = body;
var userName = "your gmail username";
var password = "your gmail password here";
var smtpClient = new SmtpClient
{
Credentials = new NetworkCredential(userName, password),
Host = smtp.gmail.com,
Port = 587,
EnableSsl = true
};
smtpClient.Send(mailMessage);
result = true;
}
catch (Exception)
{
result = false;
}
return result;
}
The piece of code you were referencing was pretty old and obselete too. CDO was used in ASP apps to send mails. I think you havent scroll down to see
Article ID: 555287 - Last Review: April 7, 2005 - Revision: 1.0
APPLIES TO
Microsoft .NET Framework 1.1
You are refering a code that is pretty old... anyways follow the code shown up, everything will be FINE...
UPDATE
My bad, I have'nt read it carefully. But
I am leaving the above code as it is, as it might be a help for you
or any other guy, who need the mailing functionality via SSL over
gmail or any other server later.
. Then in such case you need some third party app.I found you a library See here

Sending mail through http proxy

I'm trying to send emails from a system that connects to internet through a http proxy which is set in Internet Options.
i'm using SmtpClient.
Is there any way to send mails with SmtpClient through this proxy setting.
Thanks
Http Proxies control http traffic, they rarely have anything to do with SMTP at all. I've never heard of proxying SMTP before after all SMTP itself is intrinsically supports a chain of "proxies" to the destination SMTP server.
I understand that you want to use the browsers default settings, i would also like an answer for that.
Meanwhile, you could do it manually.
MailAddress from = new MailAddress("from#mailserver.com");
MailAddress to = new MailAddress("to#mailserver.com");
MailMessage mm = new MailMessage(from, to);
mm.Subject = "Subject"
mm.Body = "Body";
SmtpClient client = new SmtpClient("proxy.mailserver.com", 8080);
client.Credentials = new System.Net.NetworkCredential("from#mailserver.com", "password");
client.Send(mm);
Use MailKit
From Microsoft:
Important
We don't recommend that you use the SmtpClient class for new
development because SmtpClient doesn't support many modern protocols.
Use MailKit or other libraries instead. For more information, see
SmtpClient shouldn't be used on GitHub.
Create a console app and add MailKit
dotnet new console --framework net6.0
dotnet add package MailKit
Code to send through proxy
using MailKit.Net.Proxy;
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
var emailFromAddress = "myemail#gmail.com";
var token = "mytoken";
var to = "Someone.Else#gmail.com";
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Me", emailFromAddress));
message.To.Add(MailboxAddress.Parse(to));
message.Subject = "test";
message.Body = new TextPart("plain")
{
Text = #"This is a test."
};
using (var client = new SmtpClient())
{
client.ProxyClient = new HttpProxyClient("my-proxy.mydomain.com", 80); // <-- set proxy
client.Connect("smtp.gmail.com", 587, SecureSocketOptions.StartTls);
client.Authenticate(emailFromAddress, token);
client.Send(message);
client.Disconnect(true);
}
In this example, I've used Gmail to send the email. To do so you have to generate a token.
Go to your gmail > click on your icon on the very top right of the page > Manage your Google Account > from the menu on the left choose Security > half way down choose App Passwords > select Mail and select your device > press Generate > copy the token and replace mytoken above.
If the only access you have to the internet is through HTTP, then pretty much the only way you'll be able to do this is by setting up a VPS (or equiv) with SSH on port 443 and using corkscrew (or putty) to tunnel ssh through. From there it is a simple matter to forward smtp traffic over your ssh tunnel.
Be aware that you may be violating the companies computing policy if you do this.

Sending an email with the header return-path using windows virtual mail server

I'm trying to send an email message using the .NET MailMessage class which can also have the return-path header added so that any bounces come back to a different email address. Code is below:
MailMessage mm = new MailMessage(
new MailAddress(string.Format("{0}<{1}>", email.FromName, email.FromEmail)),
new MailAddress(emailTo));
mm.Subject = ReplaceValues(email.Subject, nameValues);
mm.ReplyTo = new MailAddress(string.Format("{0}<{1}>", email.FromName, email.FromEmail));
mm.Headers.Add("Return-Path", ReturnEmail);
// Set the email html and plain text
// Removed because it is unneccsary for this example
// Now setup the smtp server
SmtpClient smtp = new SmtpClient();
smtp.Host = SmtpServer;
smtp.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
if (SmtpUsername.Length > 0)
{
System.Net.NetworkCredential theCredential =
new System.Net.NetworkCredential(SmtpUsername, SmtpPassword);
smtp.Credentials = theCredential;
}
smtp.Send(mm);
Whenever I check the email that was sent I check the header and it always seems to be missing return-path. Is there something I am missing to configure this correctly? As I said above I'm using the standard Virtual Mail Server on my development machine (XP) however it will run on Windows 2003 eventually.
Has anyone got any ideas why it isn't coming through?
The Return-Path is set based on the SMTP MAIL FROM Envelope. You can use the Sender property to do such a thing.
Another discussion on a related issue you will have sooner or later: How can you set the SMTP envelope MAIL FROM using System.Net.Mail?
And btw, if you use SmtpDeliveryMethod.PickupDirectoryFromIis, the Sender property is not used as a MAIL FROM; you have to use Network as a delivery method to keep this value.
I did not find any workaround for this issue.
PickupDirectoryFromIis, Sender property and SMTP MAIL FROM envelope

Categories