How to add image (logo) to email sender MVC - c#

I want to be able to send an email with an image in the body. The below code works but I can't figure out how to add image to it. Thanks for any help!
namespace Identity.Areas.Birthdays.Controllers
{
public class EmailController : ApplicationBaseController
{
private EmployeeInfoEntities db = new EmployeeInfoEntities();
public ActionResult SendEmail(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
EmployeeInfo employeeInfo = db.EmployeeInfoes.Find(id);
if (employeeInfo == null)
{
return HttpNotFound();
}
return View(employeeInfo);
}
[HttpPost]
public ActionResult SendEmail(string receiver, string subject, string message, string from)
{
try
{
if (ModelState.IsValid)
{
var senderEmail = new MailAddress("test#gmail.com");
var receiverEmail = new MailAddress(receiver, "Receiver");
var password = "*********";
var sub = subject;
var body = "<font color='red'>" + "<font size='20px'>" + message + "<br />" + "<br />" + "<font color='blue'>" + from + "</font>" + "</font>" + "</font>";
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(senderEmail.Address, password)
};
using (var mess = new MailMessage(senderEmail, receiverEmail)
{
Subject = subject,
Body = body
})
{
mess.IsBodyHtml = true;
smtp.Send(mess);
ViewBag.Message = "Message Has Been Sent!";
}
return View();
}
}
catch (Exception)
{
ViewBag.Error = "An Error Has Occurred!";
}
return View();
}
}
}

You have to put image in your body string.
var body = "<img src='~/images/sample.jpg' /> <font color='red'>" + "<font size='20px'>" + message + "<br />" + "<br />" + "<font color='blue'>" + from + "</font>" + "</font>" + "</font>";
Make sure the images folder and sample.jpg exists.
Apologies, I realize the above won't work and you will get the broken image in the output because the string won't know that it has to render the image as well.
New solution, even better for cleaner body creation:
use this method.
https://lastloop.blogspot.com/2019/07/send-email-from-c.html

You will add the image tag as we add normally in the html but since you are sending it in the email, the image you want to add, has to be hosted somewhere. For example, like this google logo:
<img srce='https://www.google.com.pk/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png'/>

Related

Appended strings in message body not being sent in email using SMTPClient() and StringBuilder()

First and foremost I am very new to C# and am sure most of my code could be cleaned up so please don't suggest it unless you are also offering help with my issue.
I am sending an email via SmtpClient(). I am trying to build the body of the email using strings which are returned from functions in loops. My issue is that the string for the body isn't building how I thought it should.
Currently, I am creating a new StringBuilder() with some default text in it. I am then running some functions and trying to add the results to the StringBuilder() object via StringBuilder.AppendLine().
Here is (some of) my code:
// Setup SMTP Client for sending mail updates
//-----------------------------------
String from_addr_text = "<removed>";
String to_addr_text = "<removed>";
String msg_subject = "Updates to USPTO searches";
StringBuilder msg_body = new StringBuilder("The following searches have received updated results:" + Environment.NewLine);
SmtpClient AlertMail = new SmtpClient
{
Port = 587,
Host = "<removed>",
EnableSsl = true,
Timeout = 10000,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new System.Net.NetworkCredential("<removed>", "<removed>")
};
MailMessage update = new MailMessage(from_addr_text, to_addr_text, msg_subject, msg_body.ToString())
{
BodyEncoding = UTF8Encoding.UTF8,
IsBodyHtml = false,
DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
};
...
// Process data from api for Assignor
//-----------------------------------
bool isUpdated = false;
foreach (String url in searchesByAssignorUSPTO)
{
try
{
String longName = <removed>);
String name = <removed>;
String thisHash = await GetSearchData(url, name, "Assignor");
if (DoesHashExist(thisHash))
{
Debug.WriteLine(thisHash + " already exists. No update to " + name + " search.");
}
else
{
Debug.WriteLine(thisHash + " does not exist. There is an update to " + name + " search.");
isUpdated = true;
msg_body.AppendLine(name + " as " + "Assignor" + Environment.NewLine);
}
}
catch
{
Console.WriteLine("something is broken with ASSIGNOR search dummy!");
}
}
// Process data from api for Assignee
foreach (String url in searchesByAssigneeUSPTO)
{
try
{
String longName = <removed>;
String name = <removed>;
String thisHash = await GetSearchData(url, name, "Assignee");
if (DoesHashExist(thisHash))
{
Debug.WriteLine(thisHash + " already exists. No update to " + name + " search.");
}
else
{
Debug.WriteLine(thisHash + " does not exist. There is an update to " + name + " search.");
isUpdated = true;
msg_body.AppendLine(name + " as " + "Assignee" + Environment.NewLine);
}
}
catch
{
Console.WriteLine("something is broken with ASSIGNEE search dummy!");
}
}
// Send email is search results are updated
if (isUpdated)
{
AlertMail.Send(update);
Debug.WriteLine(msg_body.ToString());
}
When the program runs and there are results returned from the loops, msg_body is printed to the output window correctly but, when the email is received the body is only: "The following searches have received updated results:".
I have tried:
changing the value of isBodyHtml to true and used <br />
instead of Environment.NewLine.
adding \n to end of stringing and removing Environment.NewLine.
changing msg_body to type String and concatenating results to msg_body using =+.
using the Append() method instead of AppendLine().
Here is a snip of the output window:
Be sure to watch the assignment of variables in your code. When you assign msg_body to the update MailMessage object, it's only inputting the one line mentioned that is being returned in the email and doesn't include the information generated by the API.
Try moving the intialization of your SmtpClient and MailMessage variables to right before the if (isUpdated) block and you should be good to go.
per #tym32167, I needed to move the instantiation of MailMessage() to AFTER my loops and functions were completed. I was creating the object before the AppendLines() methods were called and therefore they weren't being included.

Email sending in aspnet identity

I wrote following method to send emails
public ActionResult SendEmail(UserData user)
{
try
{
#region Email content
MailMessage m = new MailMessage(
new MailAddress("sender#email.com", "Represent Location"),
new MailAddress(Reciever_Email));
m.Subject = "Mail Topic";
m.IsBodyHtml = true;
m.Body = string.Format("<img src=\"##IMAGE##\" alt=\"\"><BR/><BR/>Hi " + user.FirstName + "," + "<BR/><BR/>Your account has been successfully created with the Comp. Please click on the link below to access your account.<BR/><BR/>" + "Username - " + user.UserName + "<BR/>" + "Password - " + user.Password + "<BR/><BR/>" + "Please click here to Activate your account", user.UserName, Url.Action("ConfirmEmail", "Account", new { Token = user.Id, Email = user.UserEmail }, Request.Url.Scheme)) + string.Format("<BR/><BR/>Regards,<BR/>The Human Resource Department <BR/>");
// create the INLINE attachment
string attachmentPath = System.Web.HttpContext.Current.Server.MapPath("~/Images/logo.jpg");
// generate the contentID string using the datetime
string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "#zofm";
Attachment inline = new Attachment(attachmentPath);
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inline.ContentId = contentID;
inline.ContentType.MediaType = "image/png";
inline.ContentType.Name = Path.GetFileName(attachmentPath);
m.Attachments.Add(inline);
// replace the tag with the correct content ID
m.Body = m.Body.Replace("##IMAGE##", "cid:" + contentID);
SmtpClient smtp = new SmtpClient("Email_Server_IP");
smtp.Port = ServerPort;
smtp.Credentials = new NetworkCredential("sender#email.com", "sender_password");
smtp.EnableSsl = false;
smtp.Send(m);
#endregion
return View(user);
}
catch (Exception ex)
{
throw ex;
}
}
then I'm accessing above method in main controller like following
// Email Sending
UserData sampleData = new UserData();
sampleData.Id = user.Id;
sampleData.UserName = user.UserName;
sampleData.UserEmail = user.Email;
sampleData.FirstName = user.FirstName;
sampleData.Password = model.Password;
// await EmailController.Sendemail(sampleData);
var emailCntrl = new EmailController();
var sendEmail = emailCntrl.SendEmail(sampleData);
this is compiling without any compile times errors. but when I debug this I can see
in this line m.Body = str... I can see a error like this
because of that I'm getting an exception
Message = "Object reference not set to an instance of an object."
How can I solve this
You don't have Request, because you create just EmailController class. When controller factory creates controller for request it passes request data to Controller.Initialize Method.
Of course the best practice is to create EmailService as was mentioned above, but as answer for your question, you can make workaround. You can pass RequestContext of parent controller to EmailController in constructor and call Initialize. It's going to look like.
public EmailController()
{
}
public EmailController(RequestContext requestContext)
{
base.Initialize(requestContext);
}
And in your controller
var emailCntrl = new EmailController(this.ControllerContext.RequestContext);
var sendEmail = emailCntrl.SendEmail(sampleData);
You can also just set the ControllerContext
var emailCntrl = new EmailController(){ControllerContext = this.ControllerContext};
var sendEmail = emailCntrl.SendEmail(sampleData);
Well given that there was no request added to controller before calling action, it would be null.
There is no need for a controller there just to send the email.
Create a class/service to handle the email and pass in any dependencies
public class EmailService {
public UserData SendEmail(UserData user, string confirmationEmailUrl) {
try
{
#region Email content
MailMessage m = new MailMessage(
new MailAddress("sender#email.com", "Represent Location"),
new MailAddress(Reciever_Email));
m.Subject = "Mail Topic";
m.IsBodyHtml = true;
m.Body = string.Format("<img src=\"##IMAGE##\" alt=\"\"><BR/><BR/>Hi " + user.FirstName + "," + "<BR/><BR/>Your account has been successfully created. Please click on the link below to access your account.<BR/><BR/>" + "Username - " + user.UserName + "<BR/>" + "Password - " + user.Password + "<BR/><BR/>" + "Please click here to Activate your account", user.UserName, confirmationEmailUrl + string.Format("<BR/><BR/>Regards,<BR/>The Human Resource Department <BR/>");
// create the INLINE attachment
string attachmentPath = System.Web.HttpContext.Current.Server.MapPath("~/Images/logo.jpg");
// generate the contentID string using the datetime
string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "#zofm";
Attachment inline = new Attachment(attachmentPath);
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inline.ContentId = contentID;
inline.ContentType.MediaType = "image/png";
inline.ContentType.Name = Path.GetFileName(attachmentPath);
m.Attachments.Add(inline);
// replace the tag with the correct content ID
m.Body = m.Body.Replace("##IMAGE##", "cid:" + contentID);
SmtpClient smtp = new SmtpClient("Email_Server_IP");
smtp.Port = ServerPort;
smtp.Credentials = new NetworkCredential("sender#email.com", "sender_password");
smtp.EnableSsl = false;
smtp.Send(m);
#endregion
return user;
}
catch (Exception ex)
{
throw ex;
}
}
}
And get the action from main controller
// Email Sending
UserData sampleData = new UserData();
sampleData.Id = user.Id;
sampleData.UserName = user.UserName;
sampleData.UserEmail = user.Email;
sampleData.FirstName = user.FirstName;
sampleData.Password = model.Password;
var confirmationEmailUrl = Url.Link("Default", new { Action = "ConfirmEmail", Controller = "Account", Token = sampleData.Id, Email = sampleData.UserEmail });
var emailService = new EmailService();
var user = emailService.SendEmail(sampleData, confirmationEmailUrl);

How I can use a extern html file for a attachment in asp.net c# and send it to a email address?

How I can create a email attachment in C# and asp.net. I want use a html file that describe the attachment and I want it load in a kind of a message string in my application. Than I want do replace substrings in this message with other values that I get from a database. If the attachment is create I want to send it to a address.
I use a helpclass now but I think it is not the right way :/
I don't know whether it exist in .net libary. a kind of class or something.
What is the best way to do it?
here is the method how I make it now: namespave = using SmtpMail = EASendMail.SmtpMail;
private void SendMail(string vorname, string nachname, string anrede, string firma, string benutzername, string passwort, string von, string bis, string email)
{
SmtpMail oMail = new SmtpMail("TryIt");
SmtpClient oSmtp = new SmtpClient();
oMail.From = email;
oMail.To = email;
oMail.Subject = "Company (" + nachname + ", " + vorname + ")";
SmtpServer oServer = new SmtpServer(SMTPSERVER);
try
{
Attachment header = oMail.AddAttachment(Properties.Settings.Default.ATT_header);
Attachment footer = oMail.AddAttachment(Properties.Settings.Default.ATT_footer);
Attachment left = oMail.AddAttachment(Properties.Settings.Default.ATT_left);
Attachment right = oMail.AddAttachment(Properties.Settings.Default.ATT_right);
Attachment world = oMail.AddAttachment(Properties.Settings.Default.ATT_world);
Attachment company = oMail.AddAttachment(Properties.Settings.Default.ATT_company);
Attachment weltkarte_header = oMail.AddAttachment(Properties.Settings.Default.ATT_weltkarte);
string contentID_header = "header";
header.ContentID = contentID_header;
string contentID_footer = "footer";
footer.ContentID = contentID_footer;
string ContentID_left = "left";
left.ContentID = ContentID_left;
string ContentID_right = "right";
right.ContentID = ContentID_right;
string ContentID_world = "world";
world.ContentID = ContentID_world;
string ContentID_company = "company";
company.ContentID = ContentID_company;
string ContentID_weltkarte_header = "weltkarte_header";
weltkarte_header.ContentID = ContentID_weltkarte_header;
string htmltext = "<html><body><table width='1000px' border='0' cellpadding='0' cellspacing='0'>" +
"<tr><img src=\"cid:" + contentID_header + "\"></tr>" +
"<tr><img src=\"cid:" + ContentID_weltkarte_header + "\"></tr>" +
"<tr><table border='0' cellpadding='0' cellspacing='0'>" +
"<tr>" +
"<td><img src=\"cid:" + ContentID_left + "\"></td>" +
"<td width='880' style='background-color:#efefef;'>" +
"<p align='center'>Sie haben einen Gastzugang für [Anrede] [Vorname] [Nachname],[Firma] eingerichtet.</p>" +
"<p align='center'>Im folgenden finden Sie die Zugangsdaten,</br>" +
"die für die Anmeldung am Netzwerk benötigt werden.Weitere Informationen stehen auf der Anmeldeseite zur Verfügung.</p>" +
"<p align='center'><b>Benutzername: [Benutzername]</b><br/><b>Kennwort: [Passwort]</b></p>" +
"<p align='center'>Der Zugang wird vom [ZeitVon] bis [ZeitBis] freigeschaltet sein.</p>" +
"</td>" +
"<td><img src=\"cid:" + ContentID_right + "\"></td>" +
"</tr>" +
"</table></tr>" +
"<tr><img src=\"cid:" + ContentID_company + "\"></tr>" +
"<tr><img src=\"cid:" + contentID_footer + "\"></tr>" +
"</table></body></html>";
htmltext = htmltext.Replace("[Anrede]", anrede).Replace("[Vorname]", vorname).Replace("[Firma]", firma).Replace("[Nachname]", nachname);
htmltext = htmltext.Replace("[Benutzername]", benutzername).Replace("[Passwort]", passwort);
htmltext = htmltext.Replace("[ZeitVon]", von).Replace("[ZeitBis]", bis);
oMail.HtmlBody = htmltext;
oSmtp.SendMail(oServer, oMail);
}
catch (Exception)
{
}
}
UPDATE:
Now I have create a html file with images but I bind this images with base64 coding. it works but if I read this html in the c# application I don't can send this mail. I make a breakepoint and look in my readstring but it is all right :/
here the code:
...
SmtpMail oMail = new SmtpMail("TryIt");
SmtpClient oSmtp = new SmtpClient();
oMail.From = mail;
oMail.To = mail;
oMail.Subject = "company (" + lastname + ", " + firstname + ")";
SmtpServer oServer = new SmtpServer(SMTPSERVER);
try
{
using (StreamReader reader = new StreamReader(Server.MapPath("~/App_Data/zugangsmail.html"), System.Text.Encoding.Default))
{
string message = reader.ReadToEnd();
message = message.Replace("[Anrede]", title).Replace("[Vorname]", firstname).Replace("[Firma]", company).Replace("[Nachname]", lastname);
message = message.Replace("[Benutzername]", username).Replace("[Passwort]", password);
message = message.Replace("[ZeitVon]", from).Replace("[ZeitBis]", to);
oMail.HtmlBody = message;
oSmtp.SendMail(oServer, oMail);
}
}
catch (Exception ex)
{
error.Visible = true;
lblErrorMessage.Text = ex.Message;
}
...
Add the file as an embedded resource.
Open it and read the content
Send the content.
var assembly = Assembly.GetExecutingAssembly();
using (var stream = asssembly.GetManifestResourceStream("namespace.folder.filename))
using (StreamReader reader = new StreamReader(stream))
{
string result = reader.ReadToEnd();
}

How to attach a file to an email in c#

Hi I believe I am pretty close to figuring out what is wrong with my code, but was hoping someone could help me out or point me in the right direction. I am able to run my program and on the page where the user is going to be uploading a file it gives me the option to choose a file. But when I press submit other information gets sent to me but the file never comes. I think this is because I am having trouble figuring out where to temporarily save the file when it send to my email. Here is my code at the moment:
Also what this code is for is a comment / request page on my website where the user can comment and also add a screen shot.
private string SendMessage(string strTo, string strFrom, string strSubject, string strMessage, string strAttachment, string strBCC)
{
try
{
MailMessage mailMsg;
string strEmail = "";
string strSmtpClient = ConfigurationManager.AppSettings["SmtpClient"];
string[] arrEmailAddress = strTo.Split(';');
for (int intCtr = 0; intCtr < arrEmailAddress.Length; intCtr++)
{
strEmail = "";
if (arrEmailAddress[intCtr].ToString().Trim() != "")
{
strEmail = arrEmailAddress[intCtr].ToString().Trim();
mailMsg = new MailMessage(strFrom, strEmail, strSubject, strMessage);
mailMsg.IsBodyHtml = true;
if (!strBCC.Trim().Equals(string.Empty))
mailMsg.Bcc.Add(strBCC);
SmtpClient smtpClient = new SmtpClient(strSmtpClient);
smtpClient.UseDefaultCredentials = true;
smtpClient.Port = 25;
smtpClient.Send(mailMsg);
mailMsg.Dispose();
}
}
return "Message sent to " + strTo + " at " + DateTime.Now.ToString() + ".";
}
catch (Exception objEx)
{
return objEx.Message.ToString();
}
string strUpLoadDateTime = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strFileName1 = string.Empty;
if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
{
string strUploadFileName1 = File1.PostedFile.FileName;
strFileName1 = strUpLoadDateTime + "." + Path.GetFileNameWithoutExtension(strUploadFileName1) + Path.GetExtension(strUploadFileName1);
strFileName1 = strFileName1.Replace("'", "");
string strSaveLocation = Server.MapPath("") + "\\" + strFileName1;
File1.PostedFile.SaveAs(strSaveLocation);
txtComments.Text = "The file has been uploaded";
}
My question is where am I going wrong where in this code do I put where I want the file to be saved.
The below part of the code is what I am using to format the email when it is sent. And pick what will be sent in the email.
protected void Submit_Click1(object sender, EventArgs e)
{
try
{
string dandt = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strMessage = "Bug Name: " + txtBugName.Text.Trim() + "<br/>" +
"Module Name: " + ddlModule.SelectedValue + "<br/>" +
"Page Name: " + ddlPage.SelectedValue + "<br/>" +
"Description: " + txtComments.Text.Trim() + "<br/>" +
File1.f + "<br/>" +
"Email is" + " " + txtemail.Text.Trim() + "<br/>" +
"The request was sent at" + dandt;
SendMessage(ConfigurationManager.AppSettings["EmailAddrTo"],
ConfigurationManager.AppSettings["EmailAddrFrom"],
txtBugName.Text.Trim(),
strMessage, "", "");
}
catch
{
}
}
For some reason now nothing is sending in my emails when I press submit. Also I was trying to figure out how to put in the email the time and date the email was sent. Even though obviously my email will have this information, incase the email is delayed for some reason I would like to have the time and date the user pressed the submit button. Where is says File.F in this part of the code this is where i was trying to figure out how to get the file attachment to go to the email, but I'm not sure what syntax should go there in the code.
It looks like you are trying to attach some file from the user's computer to the email you are sending. If that is the case, you need to upload your file first before you call SendMessage.
In your Submit_Click the first thing you need to do is the code the uploads the file somewhere. Also, remove that File1.f from strMessage which is where I suspect is causing your message to null out on you.
After you upload your file, pass strSavedLocation, which is the file location you saved the file, to your SendMessage() method.
In your SendMessage method you can attach the file with the following code where you are buliding your MailMessage. strAttachment is the path name to your uploaded file:
var attachment = new Attachment(strAttachment);
// Add time stamp information for the file.
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(strAttachment);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(strAttachment);
disposition.ReadDate = System.IO.File.GetLastAccessTime(strAttachment);
mailMsg.Attachments.Add(attachment);
It looks to me like you have the major parts here minus the handy, System.Net.Mail.Attachment.
If I were doing this, I'd move the file upload handling code into the Submit_Click handler, and then just add the Mail.Attachment code.
private string SendMessage(string strTo, string strFrom, string strSubject, string strMessage, string strAttachment, string strBCC)
{
try
{
System.Net.Mail.MailMessage mailMsg;
string strEmail = "";
string strSmtpClient = ConfigurationManager.AppSettings["SmtpClient"];
string[] arrEmailAddress = strTo.Split(';');
for (int intCtr = 0; intCtr < arrEmailAddress.Length; intCtr++)
{
strEmail = "";
if (arrEmailAddress[intCtr].ToString().Trim() != "")
{
strEmail = arrEmailAddress[intCtr].ToString().Trim();
mailMsg = new MailMessage(strFrom, strEmail, strSubject, strMessage);
mailMsg.IsBodyHtml = true;
if (!strBCC.Trim().Equals(string.Empty))
mailMsg.Bcc.Add(strBCC);
/*** Added mail attachment handling ***/
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(strAttachment);
mailMsg.Attachments.Add(attachment);
SmtpClient smtpClient = new SmtpClient(strSmtpClient);
smtpClient.UseDefaultCredentials = true;
smtpClient.Port = 25;
smtpClient.Send(mailMsg);
mailMsg.Dispose();
}
}
return "Message sent to " + strTo + " at " + DateTime.Now.ToString() + ".";
}
catch (Exception objEx)
{
return objEx.Message.ToString();
}
}
protected void Submit_Click1(object sender, EventArgs e)
{
try
{
/*** Moved from SendMessage function ****/
string strUpLoadDateTime = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strFileName1 = string.Empty;
if ((File1.PostedFile != null) && (File1.PostedFile.ContentLength > 0))
{
string strUploadFileName1 = File1.PostedFile.FileName;
strFileName1 = strUpLoadDateTime + "." + Path.GetFileNameWithoutExtension(strUploadFileName1) + Path.GetExtension(strUploadFileName1);
strFileName1 = strFileName1.Replace("'", "");
string strSaveLocation = Server.MapPath("") + "\\" + strFileName1;
File1.PostedFile.SaveAs(strSaveLocation);
txtComments.Text = "The file has been uploaded";
}
string dandt = System.DateTime.Now.ToString("yyyyMMddHHmmss");
string strMessage = "Bug Name: " + txtBugName.Text.Trim() + "<br/>" +
"Module Name: " + ddlModule.SelectedValue + "<br/>" +
"Page Name: " + ddlPage.SelectedValue + "<br/>" +
"Description: " + txtComments.Text.Trim() + "<br/>" +
strSaveLocation + "<br/>" +
"Email is" + " " + txtemail.Text.Trim() + "<br/>" +
"The request was sent at" + dandt;
SendMessage(ConfigurationManager.AppSettings["EmailAddrTo"],
ConfigurationManager.AppSettings["EmailAddrFrom"],
txtBugName.Text.Trim(),
strMessage, strSaveLocation, "");
}
catch
{
}
}
As for the note about using StringBuilder, I agree, and I would use it like this:
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendFormat("Bug Name: {0}<br/>", txtBugName.Text.Trim());
sb.AppendFormat("Module Name: {0}<br/>", ddlModule.SelectedValue);
Edited To Add:
Also, see Brad's answer above about using ContentDisposition.

C# Sending Email - Sanity check

Sanity check of an email implementation please :-) Anything obvious I've missed?
string supplierOfThisMaterialEmailAddress = "davexxx#gmail.com"; // TODO
string htmlBodyIncludingReplacements = "<html><head><title>E-mail</title></head><body><div>. There has been a request on the hello.co.nz website for: " + txtMaterialDescription.Text +
"<br />Full Name: <b>" + fullName + "</b><br />" +
etc..";
string textOnlyBodyIncludingReplacements = "E-mail. There has been a request on the freematerials.co.nz website for: " + txtMaterialDescription.Text +
"Full Name: " + fullName +
"etc..";
string subject = "Someone has contacted you";
CustomMailer mailer = new CustomMailer();
string result = mailer.SendEmail(subject, htmlBodyIncludingReplacements, supplierOfThisMaterialEmailAddress, textOnlyBodyIncludingReplacements);
if (result != null)
lblMessage.Text = result;
else
lblMessage.Text = "Thank you - email has been sent";
And the class:
public class CustomMailer
{
public string SendEmail(string subject, string htmlBodyIncludingReplacements, string emailTo, string textOnlyBodyIncludingReplacements)
{
try
{
MailAddress sender = new MailAddress("dave#hello.co.nz", "Dave Mateer");
emailTo = "dave#hello.co.nz"; // testing
MailAddress recipient = new MailAddress(emailTo, null);
MailMessage message = new MailMessage(sender, recipient);
message.Subject = subject;
AlternateView textView = AlternateView.CreateAlternateViewFromString(textOnlyBodyIncludingReplacements, null, "text/plain");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlBodyIncludingReplacements, null, MediaTypeNames.Text.Html);
message.AlternateViews.Add(textView);
message.AlternateViews.Add(htmlView);
SmtpClient client = new SmtpClient();
client.Send(message);
}
catch (Exception ex)
{
throw new Exception();
}
return null;
}
}
At first glance, catching a general Exception object and throwing a new one is going to have the net effect of eating any exceptions thrown by SendEmail.
The rest looks okay.
You should change the
catch (Exception ex)
{
throw new Exception();
}
to :
catch (Exception ex)
{
throw;
}
because otherwise you lose all the data that came with the original excepion that was thrown

Categories

Resources