This question already has answers here:
How to send HTML-formatted email? [duplicate]
(3 answers)
Closed 5 years ago.
I am calling a function that sends an email in my asp.net mvc project and I want the body to be able to format as html
Here is my function that sends the email :
private void EnvoieCourriel(string adrCourriel, string text, string object, string envoyeur, Attachment atache)
{
SmtpClient smtp = new SmtpClient();
MailMessage msg = new MailMessage
{
From = new MailAddress(envoyeur),
Subject = object,
Body = text,
};
if (atache != null)
msg.Attachments.Add(atache);
msg.To.Add(adrCourriel);
smtp.Send(msg);
return;
}
The email is sent and it works like a charm, but It just shows plain html so I was wondering an argument in my instanciation of MailMessage
You just need to add the parameter IsBodyHtml to your instanciation of the MailMessage like this :
private bool EnvoieCourriel(string adrCourriel, string corps, string objet, string envoyeur, Attachment atache)
{
SmtpClient smtp = new SmtpClient();
MailMessage msg = new MailMessage
{
From = new MailAddress(envoyeur),
Subject = objet,
Body = corps,
IsBodyHtml = true
};
if (atache != null)
msg.Attachments.Add(atache);
try
{
msg.To.Add(adrCourriel);
smtp.Send(msg);
}
catch(Exception e)
{
var erreur = e.Message;
return false;
}
return true;
}
I also added a try catch because if there is a problem when trying to send the message you can show an error or just know that the email was not sent without making the application crash
I think you are looking for IsBodyHtml.
private void EnvoieCourriel(string adrCourriel, string text, string object, string envoyeur, Attachment atache)
{
SmtpClient smtp = new SmtpClient();
MailMessage msg = new MailMessage
{
From = new MailAddress(envoyeur),
Subject = object,
Body = text,
IsBodyHtml = true
};
if (atache != null)
msg.Attachments.Add(atache);
msg.To.Add(adrCourriel);
smtp.Send(msg);
return;
}
Related
When i used this code, when the email is delivered the list of addresses in bcc is visible, why please?
I use .Net Framework 4.6.2
The code works correctly, it sends the emails but when I check the To: in the email delivered I can see all the recipients that I have included in .Bcc.Add
bcc does not work as microsoft says?
public static bool SendEmails(string[] emailList, string from, string body, string subject, string attachment)
{
var result= false;
MailMessage email = null;
if (emailList!= null && !string.IsNullOrWhiteSpace(from))
{
email = new MailMessage
{
Priority = MailPriority.High,
From = new MailAddress(from),
Subject = subject,
Body = body,
BodyEncoding = Encoding.UTF8,
IsBodyHtml = true,
DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure,
};
if (!string.IsNullOrWhiteSpace(attachment))
{
email.Attachments.Add(new Attachment(attachment));
}
var smtp = new SmtpClient
{
Host = host,
Credentials =new System.Net.NetworkCredential("user","pass"),
EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["enablessl"]),
Port = int.Parse(ConfigurationManager.AppSettings["port"])
};
if (emailList.Count() > 0)
{
foreach (string email in emailList)
{
email.Bcc.Add(new MailAddress(email));
}
}
smtp.Send(email);
result= true;
}
return restul;
}
Apparently, it is necessary to include an email in emai.To.Add("anymail#anyhost.com") before starting the loop where the addresses are loaded in bcc, I don't know if this has any other consequences, but that's how it works. Email addresses are no longer displayed in the To: of the delivered message.
I am using C# MailMessage for sending Email through office 365, and I want to change the display name of the sender in the email.
I have tried using mailMessage MailAddress Constructor like this
mailMessage.From = new MailAddress("email","display name");
but it doesn't solve the problem
But when I tried to use Gmail instead, the display name is changed.
This is our generic SMTP email function. It includes the sender's email address and name.
public static bool EmailReport(
String Subject,
String Body,
String FromAddress,
String FromName
String[] To,
String[] CC,
out String sError)
{
MailMessage m = new MailMessage();
SmtpClient smtp = new SmtpClient("<insert your email server name here i.e.: mail.Mycompany.com>");
smtp.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
m.Subject = Subject;
m.Body = Body;
m.From = new MailAddress(FromAddress, FromName);
foreach (String sTo in To)
{
m.To.Add(sTo);
}
if (CC != null)
{
foreach (String sCC in CC)
{
m.CC.Add(sCC);
}
}
try
{
smtp.Send(m);
sError = "";
return true;
}
catch (Exception ex)
{
sError = ex.Message + "\r\n\r\n" + ex.StackTrace;
return false;
}
}
For some reason, when trying to initialize the properties From, Subject, and Body for a MailMessage object I can't use variables from the method parameters.
Ex - Doesn't work:
public static void MailToEML(String email, String subj, String body)
{
MailMessage mailMessage = new MailMessage
{
From = new MailAddress(email),
Subject = subj,
Body = body
};
(Rest of method irrelevant)
Ex - Works
public static void MailToEML()
{
String email = "some#email.com";
String subj = "Subject";
String body = "Contents";
MailMessage mailMessage = new MailMessage
{
From = new MailAddress(email),
Subject = subj,
Body = body
};
I've tried with List<String>, String[], and String parameters, none of them seem to work, but when they are initialized inside the method, it works flawlessly.
Error when trying with parameters:
System.FormatException: 'The specified string is not in the form required for an e-mail address.'
FIXED: Similarily, if From is correct, Subject will output the same error message, and same with Body.
Solution: Appended a \n to Subject somewhere else in the code, which the formatting did not agree with, so I just had to remove that
Calling method:
public void ExportClicked(Office.IRibbonControl control)
{
Object selObject = Globals.ThisAddIn.Application.ActiveExplorer().Selection[1];
Outlook.MailItem mailItem =
(selObject as Outlook.MailItem);
String email;
String subject;
String body;
email = mailItem.SenderEmailAddress;
subject = mailItem.Subject;
body = mailItem.Body;
if (mailItem.Subject == null)
{
subject = ThisAddIn.lang[1]; //Array element determines language, not important here
}
ThisAddIn.MailToEML(email, subject, body);
}
(Just want to mention that I will be making these an array or list if I find a solution)
After searching around for a while, I figured out I was making this a lot more complicated than it really was. Instead of several string values, I used a MailItem object.
This is the new MailToEml() method:
public static void MailToEML(Outlook.MailItem mail)
{
MailMessage mailMessage = new MailMessage
{
From = new MailAddress(mail.SenderEmailAddress),
SubjectEncoding = System.Text.Encoding.UTF8,
Subject = mail.Subject,
Body = mail.Body
};
What is going wrong?
I am trying to send an email but I'm getting the error in the title of the question. why doesn't an object be converted to a 'System.Net.Mail.MailMessage'.
private object message;
protected void btnSend_Click(object sender, EventArgs e)
{
String TMess = txtMessageBody.Text;
String TEmail = txtEmail.Text;
String TSub = txtSubject.Text;
//this particular email server requires us to login so
//create a set of credentials with the relevent username and password
System.Net.NetworkCredential userpass = new System.Net.NetworkCredential();
userpass.UserName = "email";
userpass.Password = "password";
//ensure the smtp client has the newly created credentials
client.Credentials = userpass;
if (TSub == "")
{
System.Windows.Forms.MessageBox.Show("Error: Enter the message.");
}
else
{
//create a new email from REPLACE_WITH_USER#gmail.com to recipient#domain.com
MailMessage message = new MailMessage("helloworld#gmail.com", txtEmail.Text);
}
//set the subject of the message, and set the body using the text from a text box
message.Subject = txtSubject.Text;
message.Body = txtMessageBody.Text;
//send the message
client.Send(message);
//clear the message box
//the email has been sent - either by displaying a message (e.g. a literal) or by redirecting them to a 'Message sent' page
txtMessageBody.Text = "";
txtEmail.Text = "";
txtSubject.Text = "";
}
var client = new SmtpClient();
var message = new MailMessage("helloworld#gmail.com", txtEmail.Text);
var subject = txtSubject.Text;
var body = txtMessageBody.Text;
message.Subject = subject;
mail.Body = body;
client.Send(message);
At the absolute minimum this should work just fine. Try adding your other code one line at a time and see where it breaks.
the problem lies in your if else loop. If it goes to the if statement ( and not the else statement) your mailmessage object doesn't exist. something that doesn't exist can't be parsed.
you can do it like this
MailMessage message = new MailMessage("helloworld#gmail.com", txtEmail.Text
if (TSub == "")
{
System.Windows.Forms.MessageBox.Show("Error: Enter the message.");
return;
}
I'm going through my app, trying to clean up some code that sends e-mails. I started creating my own emailer wrapper class, but then I figured that there must be a standard emailer class out there somewhere. I've done some searching, but couldn't find anything.
Also, is there a code base for stuff like this anywhere?
EDIT: Sorry, let me clarify.
I don't want to have this in my code any time I need to send an e-mail:
System.Web.Mail.MailMessage message=new System.Web.Mail.MailMessage();
message.From="from e-mail";
message.To="to e-mail";
message.Subject="Message Subject";
message.Body="Message Body";
System.Web.Mail.SmtpMail.SmtpServer="SMTP Server Address";
System.Web.Mail.SmtpMail.Send(message);
I created a class named Emailer, that contains functions like:
SendEmail(string to, string from, string body)
SendEmail(string to, string from, string body, bool isHtml)
And so I can just put this a single line in my code to send an e-mail:
Emailer.SendEmail("name#site.com", "name2#site.com", "My e-mail", false);
I mean, it's not too complex, but I figured there was a standard, accepted solution out there.
Something like this?
using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using MailMessage=System.Net.Mail.MailMessage;
class CTEmailSender
{
string MailSmtpHost { get; set; }
int MailSmtpPort { get; set; }
string MailSmtpUsername { get; set; }
string MailSmtpPassword { get; set; }
string MailFrom { get; set; }
public bool SendEmail(string to, string subject, string body)
{
MailMessage mail = new MailMessage(MailFrom, to, subject, body);
var alternameView = AlternateView.CreateAlternateViewFromString(body, new ContentType("text/html"));
mail.AlternateViews.Add(alternameView);
var smtpClient = new SmtpClient(MailSmtpHost, MailSmtpPort);
smtpClient.Credentials = new NetworkCredential(MailSmtpUsername, MailSmtpPassword);
try
{
smtpClient.Send(mail);
}
catch (Exception e)
{
//Log error here
return false;
}
return true;
}
}
Maybe you're looking for SmtpClient?
I use a generic class made out of this old Stack Overflow Answer.
Try this.
public bool SendEmail(MailAddress toAddress, string subject, string body)
{
MailAddress fromAddress = new MailAddress("pull from db or web.config", "pull from db or web.config");
string fromPassword = "pull from db or config and decrypt";
string smtpHost = "pull from db or web.config";
int smtpPort = 587;//gmail port
try
{
var smtp = new SmtpClient
{
Host = smtpHost,
Port = smtpPort,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
{
smtp.Send(message);
}
return true;
}
catch (Exception err)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(err);
return false;
}
}
This is a snippet from one of my projects. It's a little more feature-packed than some of the other implementations.
Using this function allows you to create an email with:
Tokens that can be replaced with actual values at runtime
Emails that contain both a text and HTML view
public MailMessage createMailMessage(string toAddress, string fromAddress, string subject, string template)
{
// Validate arguments here...
// If your template contains any of the following {tokens}
// they will be replaced with the values you set here.
var replacementDictionary = new ListDictionary
{
// Replace with your own list of values
{ "{first}", "Pull from db or config" },
{ "{last}", "Pull from db or config" }
};
// Create a text view and HTML view (both will be in the same email)
// This snippet assumes you are using ASP.NET (works w/MVC)
// if not, replace HostingEnvironment.MapPath with your own path.
var mailDefinition = new MailDefinition { BodyFileName = HostingEnvironment.MapPath(template + ".txt"), IsBodyHtml = false };
var htmlMailDefinition = new MailDefinition { BodyFileName = HostingEnvironment.MapPath(template + ".htm"), IsBodyHtml = true };
MailMessage htmlMessage = htmlMailDefinition.CreateMailMessage(email, replacementDictionary, new Control());
MailMessage textMessage = mailDefinition.CreateMailMessage(email, replacementDictionary, new Control());
AlternateView plainView = AlternateView.CreateAlternateViewFromString(textMessage.Body, null, "text/plain");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlMessage.Body, null, "text/html");
var message = new MailMessage { From = new MailAddress(from) };
message.To.Add(new MailAddress(toAddress));
message.Subject = subject;
message.AlternateViews.Add(plainView);
message.AlternateViews.Add(htmlView);
return message;
}
Assuming you have your Web.config set up for NetMail, you can call this method from a helper method like so:
public bool SendEmail(MailMessage email)
{
var client = new SmtpClient();
try
{
client.Send(message);
}
catch (Exception e)
{
return false;
}
return true;
}
SendMail(createMailMessage("to#email.com", "from#email.com", "Subject", "~/Path/Template"));