Cannot send email from asp.net using godaddy professional email account - c#

I have an asp.net web application that has an enquiry page from which i want to send the enquiries to my gmail account, I'm using godaddy professional email account for sending mail from the webpage.
But it doesn't send the email for reasons unknown to me.
This is my front end code:
<form id="contactform" name="contact_form" runat="server">
<input type="text" id="form_name" value="" runat="server" placeholder="Your Name*" required=""/>
<input type="email" id="form_email" value="" runat="server" placeholder="Your Mail*" required=""/>
<input type="text" id="form_phone" value="" runat="server" placeholder="Phone"/>
<textarea id="form_message" runat="server" placeholder="Your Message.." required=""></textarea>
<input id="form_botcheck" name="form_botcheck" type="hidden" value=""/>
<asp:Button CssClass="thm-btn bg-cl-1" runat="server" id="send" Text="Send" OnClick="send_Click" />
</form>'
This is my code behind.
I'm using...
System.Net;
System.Net.Mail;
// .......
$public static void SendEmail(string emailbody)
{
//email code snippet
// Specify the from and to email address
MailMessage mailMessage = new MailMessage("mymail#mydomain.com", "mymail#gmail.com");
// Specify the email body
mailMessage.Body = emailbody;
// Specify the email Subject
mailMessage.Subject = "Enquiry";
// Specify the SMTP server name and port number
SmtpClient smtpClient = new SmtpClient("relay-hosting.secureserver.net", 25);
// Specify your mail address and password
smtpClient.Credentials = new System.Net.NetworkCredential()
{
UserName = "mymail#mydomain.com",
Password = "mypassword"
};
// Gmail works on SSL, so set this property to true
smtpClient.EnableSsl = false;
// Finall send the email message using Send() method
smtpClient.Send(mailMessage);
}
protected void send_Click(object sender, EventArgs e)
{
Page.Validate();
if (Page.IsValid)
{
try
{
String str1 = form_name.Value;
String str2 = form_email.Value;
String str3 = form_phone.Value;
String str4 = form_message.Value;
String emailbody = "Name : " + str1 + "\r\n" + "e-mail : " + str2 + "\r\n" + "Contact Number : " + str3 + "\r\n" + "Message : " + str4 + "\r\n";
SendEmail(emailbody);
form_name.Value = "";
form_email.Value = "";
form_phone.Value = "";
form_message.Value = "";
ClientScript.RegisterStartupScript(GetType(), "hwa", "alert('Your Enquiry has been submitted');", true);
Response.Redirect(Request.Url.AbsoluteUri);
}
catch (Exception em) { Response.Write(em.Message); }
}
else
{
ClientScript.RegisterStartupScript(GetType(), "hwa", "alert('Please enter the required information and submit');", true);
}
}
This code worked 1-2 years back when I worked on another project.

Related

How to add image (logo) to email sender MVC

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

Email not sending from the server in asp.net

brief desc....
I have a application that has a few different pages, one page sends the user a new password, and another page that creates a new account and sends the user their username, password and activation link and two pdfs...
Problem... When testing locally, from the two separate pages, both are working fine and sending emails as expected.
Now when i have uploaded my application to the server, i test the same but only the new password email is sending to the user, and not the other email on the create new user page... Really strange.. i have tried the app on two different servers, again with the same outcome. only the password email sends to the user... It was working but then suddenly stopped working.. I don't understand why...
I have checked the smtp settings in iis and all is fine.. I just don't understand how it can send both email locally, but only one of the emails on the server? anybody have any incline of the issue.. ? here is my code...
private void SendActivationEmail(string password, DataTable td)
{
try
{
string activationCode = Guid.NewGuid().ToString();
this.InsertActivation.UpdateParameters["VendorName"].DefaultValue = this.DropDownList1.SelectedValue;
this.InsertActivation.UpdateParameters["ActivationCode"].DefaultValue = activationCode;
this.InsertActivation.Update();
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
StringBuilder sb = new StringBuilder();
sb.Append("<table width='100%' cellspacing='0' cellpadding='2'>");
sb.Append(
"<tr><td align='center' style='background-color: #18B5F0' colspan = '2'><b>Congleton Vendor Declaration</b></td></tr>");
sb.Append("<tr><td colspan = '2'></td></tr>");
sb.Append("<tr><td><b>Company Name: </b>");
sb.Append(this.DropDownList1.SelectedValue);
sb.Append("</td><td><b>Date: </b>");
sb.Append(DateTime.Now);
sb.Append(" </td></tr>");
sb.Append(" </td></tr>");
sb.Append("<tr><td colspan = '2'><b></b> ");
sb.Append(td);
sb.Append("</td></tr>");
sb.Append("</table>");
sb.Append("<br />");
sb.Append("<table border = '1'>");
sb.Append("<tr>");
sb.Append(string.Empty);
foreach (DataColumn column in td.Columns)
{
sb.Append("<th style = 'background-color: #D20B0C;color:#ffffff'>");
sb.Append(column.ColumnName);
sb.Append("</th>");
}
sb.Append("</tr>");
foreach (DataRow row in td.Rows)
{
sb.Append("<tr>");
foreach (DataColumn column in td.Columns)
{
sb.Append("<td>");
sb.Append(row[column]);
sb.Append("</td>");
}
sb.Append("</tr>");
}
sb.Append("</table>");
StringReader sr = new StringReader(sb.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
using (MemoryStream memoryStream = new MemoryStream())
{
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
MailMessage mm = new MailMessage();
mm.To.Add(
new MailAddress(this.NewEmail.Text)); ////this needs to be changed to sourcing dept email
mm.From = new MailAddress(ConfigurationManager.AppSettings["DefaultEmail"]);
mm.Sender = new MailAddress(ConfigurationManager.AppSettings["DefaultEmail"]);
mm.Subject = "Account Activation";
string body =
"This is an automatically generated e-mail. Please do not reply to this message.";
body += "<br /><br />To";
body += "<br /><b>" + this.DropDownList1.Text.Trim() + ".</b>";
body +=
"<br /><br />In line with our digitilisation roadmap we are changing the process for our annual Country of Origin Declaration, "
+ "this e-mail is the start of a more automated process which we hope you will find easier to use.";
body +=
"<br /><br />With this new process please ensure you have logged on and updated your information by"
+ " <font color=\"red\">January 26th, 2019.</font> The link will not be available beyond this date.";
body += "<br /><br />Please keep your credentials safe";
body += "<br /><br />*****************************************";
body += "<br /><br />Username : " + this.UserName + string.Empty;
body += "<br /><br />Password : " + password + string.Empty;
body += "<br /><br />*****************************************";
body += "<br /><br />Please click the following link to activate your account";
body += "<br /><a href = '" + this.Request.Url.AbsoluteUri.Replace(
"Congl/IndividualMail.aspx",
"Activation.aspx?ActivationCode=" + activationCode) + "'>Declaration</a>";
body += "<br /><br />Should you have any issues please contact myself or Izzy beacham. ";
body += "<br />We would appreciate your feedback.";
body += "<br /><br />With Best Regards,";
body += "<br />Janet rinda";
body +=
"<br /> ";
body +=
"<br /><br />This communication contains information which is confidential and may also be privileged. It is for the exclusive use of the addressee. "
+ "If you are not the addressee please note that any distribution, reproduction, copying, publication or use of this communication or the information is prohibited. If you have received this communication in error, please contact us immediately and also delete the communication from your computer.";
body +=
"<br /><br /><b>Important notice: This e-mail and any attachment thereof contain corporate proprietary information. "
+ "If you have received it by mistake, please notify us immediately by reply e-mail and delete this e-mail and its attachments "
+ "from your system. Thank you.</b>";
mm.Body = body;
mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "Declaration.pdf"));
mm.Attachments.Add(new Attachment(this.Server.MapPath("~/VendorHelpPage.pdf")));
mm.IsBodyHtml = true;
SmtpClient smtClient = new SmtpClient();
smtClient.DeliveryMethod = SmtpDeliveryMethod.Network;
try
{
smtClient.Send(mm);
}
catch (Exception ex)
{
this.ErrMsg = App.App.HandleError(MethodBase.GetCurrentMethod(), ex, string.Empty);
}
}
}
}
}
catch (Exception ex)
{
this.ErrMsg = App.App.HandleError(MethodBase.GetCurrentMethod(), ex, string.Empty);
}
}

Send inline image in email

Having an issue sending an image via email as an embedded image in the body.
The image file shows as an attachment which is ok but the inline image portion just shows as a red x.
Here is what I have so far
LinkedResource inline = new LinkedResource(filePath);
inline.ContentId = Guid.NewGuid().ToString();
MailMessage mail = new MailMessage();
Attachment att = new Attachment(filePath);
att.ContentDisposition.Inline = true;
mail.From = from_email;
mail.To.Add(data.email);
mail.Subject = "Client: " + data.client_id + " Has Sent You A Screenshot";
mail.Body = String.Format(
"<h3>Client: " + data.client_id + " Has Sent You A Screenshot</h3>" +
#"<img src=""cid:{0}"" />", inline.ContentId);
mail.IsBodyHtml = true;
mail.Attachments.Add(att);
Some minimal c# code to embed an image, can be:
MailMessage mailWithImg = GetMailWithImg();
MySMTPClient.Send(mailWithImg); //* Set up your SMTPClient before!
private MailMessage GetMailWithImg() {
MailMessage mail = new MailMessage();
mail.IsBodyHtml = true;
mail.AlternateViews.Add(GetEmbeddedImage("c:/image.png"));
mail.From = new MailAddress("yourAddress#yourDomain");
mail.To.Add("recipient#hisDomain");
mail.Subject = "yourSubject";
return mail;
}
private AlternateView GetEmbeddedImage(String filePath) {
LinkedResource res = new LinkedResource(filePath);
res.ContentId = Guid.NewGuid().ToString();
string htmlBody = #"<img src='cid:" + res.ContentId + #"'/>";
AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
alternateView.LinkedResources.Add(res);
return alternateView;
}
Try this
string htmlBody = "<html><body><h1>Picture</h1><br><img src=\"cid:filename\"></body></html>";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString
(htmlBody, null, MediaTypeNames.Text.Html);
LinkedResource inline = new LinkedResource("filename.jpg", MediaTypeNames.Image.Jpeg);
inline.ContentId = Guid.NewGuid().ToString();
avHtml.LinkedResources.Add(inline);
MailMessage mail = new MailMessage();
mail.AlternateViews.Add(avHtml);
Attachment att = new Attachment(filePath);
att.ContentDisposition.Inline = true;
mail.From = from_email;
mail.To.Add(data.email);
mail.Subject = "Client: " + data.client_id + " Has Sent You A Screenshot";
mail.Body = String.Format(
"<h3>Client: " + data.client_id + " Has Sent You A Screenshot</h3>" +
#"<img src=""cid:{0}"" />", att.ContentId);
mail.IsBodyHtml = true;
mail.Attachments.Add(att);
protected void Page_Load(object sender, EventArgs e)
{
string Themessage = #"<html>
<body>
<table width=""100%"">
<tr>
<td style=""font-style:arial; color:maroon; font-weight:bold"">
Hi! <br>
<img src=cid:myImageID>
</td>
</tr>
</table>
</body>
</html>";
sendHtmlEmail("from#gmail.com", "tomailaccount", Themessage, "Scoutfoto", "Test HTML Email", "smtp.gmail.com", 25);
}
protected void sendHtmlEmail(string from_Email, string to_Email, string body, string from_Name, string Subject, string SMTP_IP, Int32 SMTP_Server_Port)
{
//create an instance of new mail message
MailMessage mail = new MailMessage();
//set the HTML format to true
mail.IsBodyHtml = true;
//create Alrternative HTML view
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
//Add Image
LinkedResource theEmailImage = new LinkedResource("E:\\IMG_3332.jpg");
theEmailImage.ContentId = "myImageID";
//Add the Image to the Alternate view
htmlView.LinkedResources.Add(theEmailImage);
//Add view to the Email Message
mail.AlternateViews.Add(htmlView);
//set the "from email" address and specify a friendly 'from' name
mail.From = new MailAddress(from_Email, from_Name);
//set the "to" email address
mail.To.Add(to_Email);
//set the Email subject
mail.Subject = Subject;
//set the SMTP info
System.Net.NetworkCredential cred = new System.Net.NetworkCredential("fromEmail#gmail.com", "fromEmail password");
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = cred;
//send the email
smtp.Send(mail);
}
In addition to the comments above, I have the following additional comments:
Do not mix Attachments and AlternativeView, use one or the other. If you mix them, the inline attachments will be rendered as unknown downloads.
While Outlook and Google allow standard HTML-style "cid:att-001" this does NOT work on iPhone (late 2016 patch level), rather use pure alpha numeric "cid:att-001" -> "cid:att001"
As an aside: Outlook (even Office 2015) rendering (still the clear majority for business users) requires the use of TABLE TR TD style HTML, as it does not fully support the HTML box model.
An even more minimalistic example:
var linkedResource = new LinkedResource(#"C:\Image.jpg", MediaTypeNames.Image.Jpeg);
// My mail provider would not accept an email with only an image, adding hello so that the content looks less suspicious.
var htmlBody = $"hello<img src=\"cid:{linkedResource.ContentId}\"/>";
var alternateView = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
alternateView.LinkedResources.Add(linkedResource);
var mailMessage = new MailMessage
{
From = new MailAddress("youremail#host.com"),
To = { "recipient#host.com" },
Subject = "yourSubject",
AlternateViews = { alternateView }
};
var smtpClient = new SmtpClient();
smtpClient.Send(mailMessage);
Try This.
protected void Page_Load(object sender, EventArgs e)
{
string Themessage = #"<html>
<body>
<table width=""100%"">
<tr>
<td style=""font-style:arial; color:maroon; font-weight:bold"">
Hi! <br>
<img src=cid:myImageID>
</td>
</tr>
</table>
</body>
</html>";
sendHtmlEmail("from#gmail.com", "tomailaccount", Themessage, "Scoutfoto", "Test HTML Email", "smtp.gmail.com", 25);
}
protected void sendHtmlEmail(string from_Email, string to_Email, string body, string from_Name, string Subject, string SMTP_IP, Int32 SMTP_Server_Port)
{
//create an instance of new mail message
MailMessage mail = new MailMessage();
//set the HTML format to true
mail.IsBodyHtml = true;
//create Alrternative HTML view
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
//Add Image
LinkedResource theEmailImage = new LinkedResource("E:\\IMG_3332.jpg");
theEmailImage.ContentId = "myImageID";
//Add the Image to the Alternate view
htmlView.LinkedResources.Add(theEmailImage);
//Add view to the Email Message
mail.AlternateViews.Add(htmlView);
//set the "from email" address and specify a friendly 'from' name
mail.From = new MailAddress(from_Email, from_Name);
//set the "to" email address
mail.To.Add(to_Email);
//set the Email subject
mail.Subject = Subject;
//set the SMTP info
System.Net.NetworkCredential cred = new System.Net.NetworkCredential("fromEmail#gmail.com", "fromEmail password");
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.UseDefaultCredentials = false;
smtp.Credentials = cred;
//send the email
smtp.Send(mail);
}
The other solution is attaching the image as attachment and then referencing it html code using cid.
HTML Code:
<html>
<head>
</head>
<body>
<img width=100 height=100 id=""1"" src=""cid:Logo.jpg"">
</body>
</html>
C# Code:
EmailMessage email = new EmailMessage(service);
email.Subject = "Email with Image";
email.Body = new MessageBody(BodyType.HTML, html);
email.ToRecipients.Add("abc#xyz.com");
string file = #"C:\Users\acv\Pictures\Logo.jpg";
email.Attachments.AddFileAttachment("Logo.jpg", file);
email.Attachments[0].IsInline = true;
email.Attachments[0].ContentId = "Logo.jpg";
email.SendAndSaveCopy();
Example on how to embed multiple images into an HTML email. Note, if you try to use newer HTML elements such as flexbox you will have trouble. If you use a simple table it will work. When I tried with flexbox the styling wasn't recognized.
public static void Main(string[] args)
{
var html = File.ReadAllText("c:\test.html");
var altView = GetAlternateView(html);
SendEmail(new List<MailRecipients> {new MailAddress(someone#email.com)}, "Hello!", "Images in Email Test!", true, altView);
}
public static bool SendEmail(List<MailAddress> recipients, string body, string subject, bool html, AlternateView view, MailPriority priority = MailPriority.Normal)
{
try
{
MailMessage message = new MailMessage();
SmtpClient smtp = new SmtpClient();
message.From = new MailAddress(ConfigLookup.GetStringValue(ConfigNames.EmailFrom));
recipients.ForEach(r => message.To.Add(new MailAddress(r.Address)));
message.Subject = subject;
message.IsBodyHtml = html;
message.AlternateViews.Add(view);
message.Priority = priority;
smtp.Port = 25;
smtp.Host = youremailhost;
smtp.EnableSsl = yes;
smtp.UseDefaultCredentials = false;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(message);
return true;
}
catch (Exception e)
{
return false;
}
}
private AlternateView GetAlternateView(string html)
{
var logoPath = ConfigLookup.GetStringValue(ConfigNames.LogoPath);
LinkedResource logoResource = new LinkedResource(logoPath);
// ContentID must match the 'cid:contentId' in the html
logoResource.ContentId = "logo";
// Without a Mime type the images will show up as attached .bin files
logoResource.ContentType = new ContentType("image/png");
logoResource.TransferEncoding = TransferEncoding.Base64;
var heroPath = ConfigLookup.GetStringValue(ConfigNames.HeroPath);
LinkedResource heroResource = new LinkedResource(heroPath);
// ContentID must match the 'cid:contentId' in the html
heroResource.ContentId = "hero";
// Without a Mime type the images will show up as attached .bin files
heroResource.ContentType = new ContentType("image/png");
heroResource.TransferEncoding = TransferEncoding.Base64;
AlternateView alternateView = AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html);
alternateView.LinkedResources.Add(logoResource);
alternateView.LinkedResources.Add(heroResource);
return alternateView;
}
In your Html, the main thing that links up the images to the LinkedResource is the 'cid:contentId' must match:
<a href="https://somesite.com" target="_blank" style="color:#033254;">
<img src="cid:logo" width="218" alt="Company logo" style="max-width:100%;height:auto;" />
</a>
<a href="https://somesite.com" target="_blank" style="color:#033254;">
<img src="cid:hero" width="218" alt="Company hero" style="max-width:100%;height:auto;" />
</a>
Full HTML:
<!DOCTYPE html>
<html lang="en" xmlns="https://www.w3.org/1999/xhtml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="x-apple-disable-message-reformatting">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>Shipping Confirmation from Products Company</title>
</head>
<body style="margin:0;padding:0;word-spacing:normal;">
<div role="article" aria-roledescription="email" lang="en" style="-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;background-color:#ffffff;">
<table width="100%" align="center" border="0" cellpadding="0" cellspacing="0" role="presentation" >
<tr>
<td align="center">
<div class="outer" style="width:96%;max-width:660px;margin:20px auto;background-color:#ffffff;">
<table role="presentation" width="100%" border="0" cellpadding="0" cellspacing="0">
<tr style="background-color:rgb(35, 68, 107);">
<td align="center" style="padding:20px 0;">
<a href="https://yahoo.com" target="_blank" style="color:#033254;">
<img src="cid:logo" width="218" alt="Products Company logo" style="max-width:100%;height:auto;" />
</a>
</td>
</tr>
<tr style="background-color:#ffffff;;">
<td align="center" style="padding:20px 0;">
<a href="https://yahoo.com" target="_blank" style="color:#033254;">
<img src="cid:hero" width="400" alt="Products Company hero" style="max-width:100%;height:auto;" />
</a>
</td>
</tr>
<tr style="background-color:rgb(35, 68, 107);">
<td style="padding:32px; text-align:center;">
<h1 style="margin-top:0;margin-bottom:16px;font-family:Arial,sans-serif;font-size:24px;line-height:30px;letter-spacing:1px;font-weight:bold;color:#ffffff;">
Shipping Confirmation
</h1>
<hr style="border:0;background-color:rgb(35, 68, 107);border-bottom:.5px solid #ffffff;width:66%;"/>
<h3 style="margin:16px 0;font-family:Arial,sans-serif;font-size:18px;line-height:24px;letter-spacing:1px;font-weight:bold;color:#ffffff;">Order# {0}</h3>
<h3 style="margin:16px 0;font-family:Arial,sans-serif;font-size:18px;line-height:24px;letter-spacing:1px;font-weight:bold;color:#ffffff;">{1}</h3>
<p style="margin:24px 0 8px;font-family:Arial,sans-serif;font-size:16px;line-height:22px;letter-spacing:.5px;color:#ffffff;">Thank you for your order!</p>
<p style="margin:8px 0 8px;font-family:Arial,sans-serif;font-size:16px;line-height:22px;letter-spacing:.5px;color:#ffffff;">Good news! It's on its way.</p>
<p style="margin:8px 0 8px;font-family:Arial,sans-serif;font-size:16px;line-height:22px;letter-spacing:.5px;color:#ffffff;">You can find the shipping details below.</p>
<h3 style="margin:16px 0;font-family:Arial,sans-serif;font-size:18px;line-height:24px;letter-spacing:1px;font-weight:bold;color:#ffffff;">
<a style="color:#ffffff;" href="https://www.ups.com/mobile/track?trackingNumber={2}">
[Track my package!]
</a>
</h3>
<p style="margin:32px 0 8px;font-family:Arial,sans-serif;font-size:16px;line-height:22px;letter-spacing:.5px;font-weight:bold;color:#ffffff;">Please contact Customer Service if you have any questions.</p>
<p style="margin:8px 0 8px;font-family:Arial,sans-serif;font-size:16px;line-height:22px;letter-spacing:.5px;color:#ffffff;">Customer Service:
<a style="color:#ffffff;" href="tel:18003665412">1-800-888-8888</a> ext. 8888
</p>
</td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</div>
</body>
</html>
We all have our preferred coding styles. This is what I did:
var pictures = new[]
{
new { id = Guid.NewGuid(), type = "image/jpeg", tag = "justme", path = #"C:\Pictures\JustMe.jpg" },
new { id = Guid.NewGuid(), type = "image/jpeg", tag = "justme-bw", path = #"C:\Pictures\JustMe-BW.jpg" }
}.ToList();
var content = $#"
<style type=""text/css"">
body {{ font-family: Arial; font-size: 10pt; }}
</style>
<body>
<h4>{DateTime.Now:dddd, MMMM d, yyyy h:mm:ss tt}</h4>
<p>Some pictures</p>
<div>
<p>Color Picture</p>
<img src=cid:{{justme}} />
</div>
<div>
<p>Black and White Picture</p>
<img src=cid:{{justme-bw}} />
</div>
<div>
<p>Color Picture repeated</p>
<img src=cid:{{justme}} />
</div>
</body>
";
// Update content with picture guid
pictures.ForEach(p => content = content.Replace($"{{{p.tag}}}", $"{p.id}"));
// Create Alternate View
var view = AlternateView.CreateAlternateViewFromString(content, Encoding.UTF8, MediaTypeNames.Text.Html);
// Add the resources
pictures.ForEach(p => view.LinkedResources.Add(new LinkedResource(p.path, p.type) { ContentId = p.id.ToString() }));
using (var client = new SmtpClient()) // Set properties as needed or use config file
using (MailMessage message = new MailMessage()
{
IsBodyHtml = true,
BodyEncoding = Encoding.UTF8,
Subject = "Picture Email",
SubjectEncoding = Encoding.UTF8,
})
{
message.AlternateViews.Add(view);
message.From = new MailAddress("me#me.com");
message.To.Add(new MailAddress("you#you.com"));
client.Send(message);
}
You need to add the LinkedResource into an AlternateView
AlternateView alternateView = AlternateView.CreateAlternateViewFromString("<h3>Client: " + data.client_id + " Has Sent You A Screenshot</h3>" +
#"<img src=""cid:{0}"" />", null, "text/html");
alternateView.LinkedResources.Add(inline);
mail.AlternateViews.Add(alternateView);
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("userid#gmail.com");
mail.To.Add("userid#gmail.com");
//set the content
mail.Subject = "Sucessfully Sent the HTML and Content of mail";
//first we create the Plain Text part
string plainText = "Non-HTML Plain Text Message for Non-HTML enable mode";
AlternateView plainView = AlternateView.CreateAlternateViewFromString(plainText, null, "text/plain");
XmlTextReader reader = new XmlTextReader(#"E:\HTMLPage.htm");
string[] address = new string[30];
string finalHtml = "";
var i = -1;
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{ // The node is an element.
if (reader.AttributeCount <= 1)
{
if (reader.Name == "img")
{
finalHtml += "<" + reader.Name;
while (reader.MoveToNextAttribute())
{
if (reader.Name == "src")
{
i++;
address[i] = reader.Value;
address[i] = address[i].Remove(0, 8);
finalHtml += " " + reader.Name + "=" + "cid:chartlogo" + i.ToString();
}
else
{
finalHtml += " " + reader.Name + "='" + reader.Value + "'";
}
}
finalHtml += ">";
}
else
{
finalHtml += "<" + reader.Name;
while (reader.MoveToNextAttribute())
{
finalHtml += " " + reader.Name + "='" + reader.Value + "'";
}
finalHtml += ">";
}
}
}
else if (reader.NodeType == XmlNodeType.Text)
{ //Display the text in each element.
finalHtml += reader.Value;
}
else if (reader.NodeType == XmlNodeType.EndElement)
{
//Display the end of the element.
finalHtml += "</" + reader.Name;
finalHtml += ">";
}
}
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(finalHtml, null, "text/html");
LinkedResource[] logo = new LinkedResource[i + 1];
for (int j = 0; j <= i; j++)
{
logo[j] = new LinkedResource(address[j]);
logo[j].ContentId = "chartlogo" + j;
htmlView.LinkedResources.Add(logo[j]);
}
mail.AlternateViews.Add(plainView);
mail.AlternateViews.Add(htmlView);
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Credentials = new NetworkCredential(
"userid#gmail.com", "Password");
smtp.EnableSsl = true;
Console.WriteLine();
smtp.Send(mail);
}
I added the complete code below to display images in Gmail,Thunderbird and other email clients :
MailMessage mailWithImg = getMailWithImg();
MySMTPClient.Send(mailWithImg); //* Set up your SMTPClient before!
private MailMessage getMailWithImg()
{
MailMessage mail = new MailMessage();
mail.IsBodyHtml = true;
mail.AlternateViews.Add(getEmbeddedImage("c:/image.png"));
mail.From = new MailAddress("yourAddress#yourDomain");
mail.To.Add("recipient#hisDomain");
mail.Subject = "yourSubject";
return mail;
}
private AlternateView getEmbeddedImage(String filePath)
{
// below line was corrected to include the mediatype so it displays in all
// mail clients. previous solution only displays in Gmail the inline images
LinkedResource res = new LinkedResource(filePath, MediaTypeNames.Image.Jpeg);
res.ContentId = Guid.NewGuid().ToString();
string htmlBody = #"<img src='cid:" + res.ContentId + #"'/>";
AlternateView alternateView = AlternateView.CreateAlternateViewFromString(htmlBody,
null, MediaTypeNames.Text.Html);
alternateView.LinkedResources.Add(res);
return alternateView;
}
sending 2 images vb.net code convert for C# online converter.
Public Function SendEmail(Optional ByVal p_AsHTML As Boolean = False, Optional ByVal p_themEmail As String = "") As Boolean
Dim client As SmtpClient = New SmtpClient ''("FMSERVER.FMINNOVATIONS.COM.AU")
'Dim fromAddress As MailAddress = New MailAddress(Me.FromEmail, "WSMenterprise")
'Dim toAddress As MailAddress
Try
Dim aMessage As New MailMessage()
'(New MailAddress(Me.FromEmail, "WSMenterprise"), New MailAddress(anAdd))
If _fromAddress IsNot Nothing Then
If _fromName IsNot Nothing Then
aMessage.From = New MailAddress(_fromAddress, _fromName)
Else
aMessage.From = New MailAddress(_fromAddress)
End If
End If
For Each anAdd As String In _To
aMessage.To.Add(New MailAddress(anAdd))
Next
For Each cc As String In _CC
aMessage.CC.Add(New MailAddress(cc))
Next
For Each bcc As String In _BCC
aMessage.Bcc.Add(New MailAddress(bcc))
Next
aMessage.Subject = _Subject
aMessage.IsBodyHtml = p_AsHTML
If _EmailLogo Is Nothing Then
aMessage.Body = _Body
Else
If p_themEmail.ToString().ToLower.Contains("dexus") Then
Dim htmlView = AlternateView.CreateAlternateViewFromString(_Body.ToString(), Nothing, "text/html")
Dim logo As New LinkedResource(_EmailLogo)
logo.ContentId = "Dexuslogo1"
Dim logo1 As New LinkedResource(_EmailLogo1)
logo1.ContentId = "Dexuslogo2"
htmlView.LinkedResources.Add(logo)
htmlView.LinkedResources.Add(logo1)
aMessage.AlternateViews.Add(htmlView)
Else
Dim htmlView = AlternateView.CreateAlternateViewFromString(_Body.ToString(), Nothing, "text/html")
Dim logo As New LinkedResource(_EmailLogo)
logo.ContentId = "companylogo"
htmlView.LinkedResources.Add(logo)
aMessage.AlternateViews.Add(htmlView)
End If
End If
For Each anAttach As Attachment In _Attachments
aMessage.Attachments.Add(anAttach)
Next
If _ReplyTo IsNot Nothing Then aMessage.ReplyToList.Add(New MailAddress(_ReplyTo))
client.Host = "smtpi.cbre.com.au"
client.UseDefaultCredentials = True
client.Send(aMessage)
Catch exRecipUnk As SmtpFailedRecipientException
Return False
Catch exSmtp As SmtpException
''exSmtp.StatusCode
Return False
Catch ex As Exception
Return False
End Try
Return True
End Function
If p_Gmap_code = "DE" Then
Dim p_Theme As New Theme("Dexus")
Dim passwordlink As String = ""
Dim DexuslogoImage1 As String = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images\Dexus_Notice_Logo.png")
Dim DexuslogoImage2 As String = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images\DexusTenantNotice.png")
passwordlink = "<a href='" + p_Theme.TenantLoginPage + "?accesstype=email&te=" + a.Encrypt(p_TenantEmail) + "' target='_blank'>here.</a><br/>"
bodys += "<div align='Center'><table border='0' cellpadding='0' cellspacing='0'><tr style='height:50px;'><td width='623px' ></td><td valign='top' width='180'><p align='right'><a href='http://www.dexus.com/'><img border='0' height='50' src=cid:Dexuslogo1 width='174' alt=''/></a></p></td></tr><tr><td colspan='2' width='803' style='height:25px;'></td></tr> <tr><td width='623px'><p align='left' style='font-family:Arial;font-size:14pt;'><strong> Your Dexus Response Password is about to expire</strong></p></td>"
bodys += " <td width='180'><p align='right' style='font-family:Arial;font-size:10pt;'>" + DateTime.Now.ToString("dd/MM/yyyy") + " </p>"
bodys += "</td></tr><tr><td colspan='2' width='803' style='height:30px;'> </td></tr> <tr> <td colspan='2' width='803' style='font-family:Arial;font-size:10pt;'>"
bodys += "<p>" + wishes + " " + p_TenantName.Trim().ToString() + "</p>"
bodys += "</td></tr><tr><td colspan='2' width='803' style='height:25px;'></td> </tr><tr><td colspan='2' width='803' style='font-family:Arial;font-size:10pt;'>"
bodys += "Your Dexus Response password is about to expire in " + p_remaindays.ToString() + " days.<br /><br /> To reset your password and update your details, please click " + passwordlink.ToString() + "<br /><br />Please note that if you do not update your password by " + p_date + ",then your account will be set to inactive and you will not be able to access Dexus Response.</br></br>Please contact Dexus Response if you require assistance in accessing the portal.</p></td>" 'edit
bodys += " </tr><tr><td colspan='2' width='803' style='height:30px;'></td></tr><tr><td colspan='2' width='803'><table align='left' border='0' cellpadding='0' cellspacing='0'><tr><td width='802' style='font-family:Arial;font-size:10pt;'><p><strong>Dexus Response</strong></p></td></tr><tr><td width='802' style='font-family:Arial;font-size:10pt;'><p><a href='mailto:property.services#dexusfm.com'>property.services#dexusfm.com</a> <strong>|</strong> 1300 339 870 <strong>|</strong> <a href='https://response.dexus.com/'>response.dexus.com</a></p></td></tr></table></td></tr><tr><td colspan='2' width='803' style='height:15px;'></td></tr><tr> <td colspan='2' width='803'><p> </p><p><a href='https://response.dexus.com/' border='0' target='_blank'><img border='0' height='133'"
bodys += "src=cid:Dexuslogo2 alt='' width='800' /></a></p></td></tr><tr><td colspan='2' width='803' style='height:10px;'></td></tr><tr><td colspan='2' width='803' style='font-family:Arial;font-size:10pt;'><p><a href='http://www.dexus.com/who-we-are/terms-and-conditions' style=' color:#000000;'>Terms and Conditions</a><strong> | </strong><a href='http://www.dexus.com/who-we-are/privacy-policy' style=' color:#000000;'> Privacy Policy</a></p></td></tr><tr><td colspan='2' width='803' style='height:40px;'></td></tr><tr><td colspan='2' width='803'><p></p></td></tr><tr><td colspan='2' width='803' style='height:10px;'></td></tr><tr></tr><tr><td colspan='2' width='803' style='height:20px;'></td></tr></table></div>"
email = New Common.Email(emailHeading, bodys, p_Theme.EmailFrom, DexuslogoImage1, DexuslogoImage2)
email.ToEmail = p_TenantEmail
email.SendEmail(True, p_Theme.EmailFrom)

How to avoid sending duplicate mail in c#

I have written a code which sends mail to the admin for moderation whenever a user adds a content from front end.....the problem is sometimes the admin gets two mails of same content.
below is my code
MailMessage mail = new MailMessage();
string mailto = ConfigurationManager.AppSettings["adminStoryEmail"].ToString();
mail.To.Add(mailto);
//mail.To.Add("vidyasagar.patil#viraltech.in");
mail.From = new MailAddress(ConfigurationManager.AppSettings["fromEmail"]);
mail.Subject = ConfigurationManager.AppSettings["email_subject"];
if (uploadedpath != "")
{
mail.Body = "Email ID : " + txtEmail.Text + "<br /> Title : " + txtStoryTitle.Text + "<br />" + " Download : " + " http://www.achievewithdell.in/uploads/" + uploadedpath + "<br />";
if (story != "")
{
mail.Body += "New story has been added" + " http://www.achievewithdell.in/admin/ManageStory.aspx";
}
}
else
{
mail.Body = "Email ID : " + txtEmail.Text + "<br /> Title : " + txtStoryTitle.Text + " <br />";
if (story != "")
{
mail.Body += "New story has been added" + " http://www.achievewithdell.in/admin/ManageStory.aspx";
}
}
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["smtp_host"]; //Or Your SMTP Server Address
smtp.Port = 25;
smtp.Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["smtp_userid"], ConfigurationManager.AppSettings["smtp_password"]); //Or your Smtp Email ID and Password
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(mail);
You say sometimes the email gets sent twice. This would suggest the code you've given us is fine, the problem probably lies with what calls that code.
One way you could eliminate duplicates is to queue up your mails to be sent, perhaps in a database (storing: to, from, subject, body etc). Then periodically, iterate through mails to be sent, ignoring duplicates and marking sent mails so they don't get sent again.
Failing a refactor to your application like that, as the other poster suggested, get out your debugger and set a breakpoint. Depending on your version of Visual Studio, you could use the Breakpoint Hit Count so you only land at the breakpoint on the 2nd time.
Debug and make sure smtp Send() method is not called twice, put a break point on that line.

Email Body Format Problem

i had a problem in format in email. I want to have a new line..
here's the format in email..
Name: sdds Phone: 343434 Fax: 3434 Email: valencia_arman#yahoo.com Address: dsds Remarks: dsds Giftwrap: Yes Giftwrap Instructions: sdds Details: PEOPLE OF THE BIBLE(SCPOTB-8101-05) 1 x Php 275.00 = Php 275.00 Total: Php275.00
here's my C# code..
mail.Body = "Name: " + newInfo.ContactPerson + Environment.NewLine
+ "Phone: " + newInfo.Phone + Environment.NewLine
+ "Fax: " + newInfo.Fax + Environment.NewLine
+ "Email: " + newInfo.Email + Environment.NewLine
+ "Address: " + newInfo.Address + Environment.NewLine
+ "Remarks: " + newInfo.Notes + Environment.NewLine
+ "Giftwrap: " + rbGiftWrap.SelectedValue + Environment.NewLine
+ "Giftwrap Instructions: " + newInfo.Instructions + Environment.NewLine + Environment.NewLine
+ "Details: " + Environment.NewLine
+ mailDetails;
If you're sending it in HTML, make sure you set the format.
mail.BodyFormat = MailFormat.Html;
And then you can use <br/> should you want to.
UPDATE:
Try this as an alternative:
using System.Net.Mail;
...
MailMessage myMail;
myMail = new MailMessage();
myMail.IsBodyHtml = true;
maybe you can try this...
We create seperate email templates (e.g. EmailTemplate.htm), it includes the message to be sent. You will have no problems for new line in message.
Then this is our Code behind:
private void SendEmail()
{
string emailPath = "../EmailTemplate.htm"; //Define your template path here
string emailBody = string.Empty;
StreamReader sr = new StreamReader(emailPath);
emailBody = sr.ReadToEnd();
sr.Close();
sr.Dispose();
//Send Email; you can refactor this out
MailMessage message = new MailMessage();
MailAddress address = new MailAddress("sender#domain.com", "display name");
message.From = address;
message.To.Add("to#domain.com");
message.Subject = "Your Subject";
message.IsBodyHtml = true; //defines that your email is in Html form
message.Body = emailBody;
//smtp is defined in web.config
SmtpClient smtp = new SmtpClient();
try
{
smtp.Send(message);
}
catch (Exception ex)
{
//catch errors here...
}
}
Did you try "+\n" instead of Environment.NewLine?

Categories

Resources