updating Classic ASP email code to c# Asp.Net - c#

I have written many apps that send emails , normally I create an SMTP client , authenticate with username and password , and that's it! I am now updating some OLD classic ASP code where they sent an email like so :
Set objMessage = Server.CreateObject("CDO.Message")
objMessage.To = strTo
objMessage.From = strFrom
objMessage.Bcc = strBcc
objMessage.Subject = strSubject
objMessage.TextBody = strBody
objMessage.Send
Set objMessage = Nothing
I've Google'd and found that obviously the CDO objects were deprecated long ago,
my question is :
Is this code above actually able to send emails without creating some type of client with authentication?? AND what is the best way to update this code with using c# 4.5 ??

CDO is an ActiveX component. It wasn't created for ASP specifically, but it pretty much became the de facto way to bodge email into your ASP applications. It becomes your SMTP client and generally uses a local SMTP server to relay email to another SMTP server for onward transmission.
To send emails in the land of .Net 4.5 using C#, use
//Create a Smtp client, these settings can be set in the web.config and
//you can use the parameterless constructor
SmtpClient client=new SmtpClient("some.server.com");
//If you need to authenticate
client.Credentials=new NetworkCredential("username", "password");
//Create the message to send
MailMessage mailMessage = new MailMessage();
mailMessage.From = "someone#somewhere.com";
mailMessage.To.Add("someone.else#somewhere-else.com");
mailMessage.Subject = "Hello There";
mailMessage.Body = "Hello my friend!";
//Send the email
client.Send(mailMessage);

Related

Sending mail with MimeKit and default email

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.

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);

The SMTP server requires a secure connection or the client was not authenticated - Error

I am trying to send email using Amazon SES.
I am able to send email by using our local SMTPserver and also able to send email by using sample provided at amazon website.
I need to send send From Address & To Address names with the email. I can not do this with SendEmailRequest class provided in the Amazon SDK, because there is no such overload for WithSource(toaddress), WithDestination(destinationaddress) & WithReplyToAddresses(replytoaddress) methods so i can't pass names form sender 7 receiver here, so that I am using regular method of sending mail using Amazon configurations.
I tried both way pass credentials by the hard coding through code as well as by puyting configuration by file but still I am getting same error for both ways above this error when using port 587,
"The SMTP server requires a secure connection or the client was not authenticated. The server response was: Authentication required"
when tried with 465 port getting this error,
"Failure Sending Email"
When tried putting IP address instead of host address of amazon server got this error.
"The remote certificate is invalid according to the validation procedure."
Please suggest me what I am missing here,
Here is my code,
MailMessage mail = new MailMessage();
mail.From = new System.Net.Mail.MailAddress(FromEmail, FromName);
SmtpClient smtp = new SmtpClient("email-smtp.us-east-1.amazonaws.com", 587);
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential(AWSAccessKey, AWSSecretKey);
//recipient address
mail.To.Add(new MailAddress(ToEmail, ToName));
//Formatted mail body
mail.IsBodyHtml = true;
mail.Body = strBody;
smtp.Send(mail);
Thanks in Advance..!!!
I solved this problem by passing email with email user name in the following in the format
User Name< example#domain.com >
Sample from Amazon site is already working for me,
here is my working code,
AWSCredentials objAWSCredentials = new BasicAWSCredentials(AWSAccessKey, AWSSecretKey);
Destination destination = new Destination().WithToAddresses(new List<string>() { TO });
// Create the subject and body of the message.
Content subject = new Content().WithData(SUBJECT);
Content textBody = new Content().WithData(BODY);
Body body = new Body().WithHtml(textBody);
//Body body = new Body().WithText(textBody);
// Create a message with the specified subject and body.
Message message = new Message().WithSubject(subject).WithBody(body);
// Assemble the email.
SendEmailRequest request = new SendEmailRequest().WithSource(FROM).WithDestination(destination).WithMessage(message).WithReplyToAddresses(REPLYTO);
// Instantiate an Amazon SES client, which will make the service call. Since we are instantiating an
// AmazonSimpleEmailServiceClient object with no parameters, the constructor looks in App.config for
// your AWS credentials by default. When you created your new AWS project in Visual Studio, the AWS
// credentials you entered were added to App.config.
AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(objAWSCredentials);
// Send the email.
Console.WriteLine("Attempting to send an email through Amazon SES by using the AWS SDK for .NET...");
client.SendEmail(request);
here I've passed FROM, TO & ReplyToAddress in this format,
User Name< example#domain.com >

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 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