C# SMTP sends email with empty body in productive enviroment - c#

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

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.

updating Classic ASP email code to c# Asp.Net

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

Send an email from the logged in user ASP.NET

I have created a webform in visual studio. This application is sending an email.
BUT I want the FROM address to be the logged in user's email. So for example, if John is logged in with his email and password and he clicks submit, the email will send to Person X but the from address will come from John. I hope this is a clear enough explanation.
This is the code snippet of my sending mail method.
{
MailMessage message = new MailMessage();
message.To.Add(nameddl.Text);
message.From = new MailAddress("");
message.Subject = "Notification";
message.Body = "An new entry has been made that requires your attention.";
message.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
}
So this line, message.From = new MailAddress(User.LoggedIn); this is what I want. BUT how do one code it to work like that, can it be made possible?
NB: This is NOT a MVC Application, just a regular ASP.NET Web form.
**EDIT Still struggling with this one, so if anyone got an idea that would be great?
If you are storing email in session then you can directly pass it like.
message.From = new MailAddress(Session["Email"].Tostring);
if this is not the case and you have stored email in database then you can get it from there by simply making one method that return email address.like
message.From = GetEmail();

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 >

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