Using the simple SMTP C# code below to send an email, how can i send an email template?
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add(toEmailAddress);
message.Subject = "subject";
message.From = new System.Net.Mail.MailAddress(from);
message.Body = "http://www.yoursite.com/email.htm";
message.IsBodyHtml = true;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("server");
smtp.Send(message);
Currently, as expected the received email just contains the URL for the template. how can i get it to send the template?
System.Net.WebClient client = new System.Net.WebClient();
string html = client.DownloadString("http://www.yoursite.com/email.htm");
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add(toEmailAddress);
message.Subject = "subject";
message.From = new System.Net.Mail.MailAddress(from);
message.Body = html;
message.IsBodyHtml = true;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("server");
smtp.Send(message);
Your question is actually about reading a string from url and one of the possible answers is:
var url = "http://www.yoursite.com/email.htm";
var body = "";
using(var client = new WebClient()) {
body = client.DownloadString(url);
}
If the file is local, instead of using a download, you can simply read it in using System.IO, such as
string html;
System.IO.StreamReader fstream;
fstream = File.OpenText("yourpathgoeshere.html");
html = fstream.ReadToEnd();
fstream.Close();
after this, just assign the rest of the properties as suggested in the other posts. If the html file you're after is stored locally, this is probably better, or if it will be accessed frequently, it may be a better idea to store it locally and use this method.
note, you will need to import System.IO for this to work correctly.
Related
string html = "<img src=data:image/png;base64,i0KGgAD34DtaA..........*>"; //*very long
SensMail(mailaddress,html, System.Text.Encoding.UTF8);
public static void SensMail(string sendTo, string body, System.Text.Encoding enCode)
{
string emailaddress = "mail#gmail.com";
string password = "it's secret";
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient();
mail.From = new MailAddress(sendTo);
mail.To.Add(sendTo);
mail.BodyEncoding = enCode;
mail.IsBodyHtml = true;
mail.Subject = "subject";
mail.Body = body;
SmtpServer.UseDefaultCredentials = false;
NetworkCredential NetworkCred = new NetworkCredential(emailaddress,password);
SmtpServer.Credentials = NetworkCred;
SmtpServer.EnableSsl = true;
SmtpServer.Port = 587;
SmtpServer.Host = "smtp.gmail.com";
SmtpServer.Send(mail);
}
Why is the image not displayed ??
I tried to send to two different email providers, without success.
Is this happening for security reasons?
How can this problem be solved?
In HTML it does work and you see the image.
Outlook doesn't understand base64 images. There are two possible ways:
Upload the image file to any web server and then use the image URL in the HTML body for that image. Be aware, Outlook may block external links (even for images) automatically.
You may add an image file as an attachment and then use the cid prefix for the img tag. See Send inline image in email for more information.
This is a class from my code.
string to = message.Text;
string from = "noreply#zayzaycorporation.onmicrosoft.com";
MailMessage messagex = new MailMessage(from, to);
string mailbody = "Welcome!";
messagex.Subject = "Hello";
messagex.Body = mailbody;
messagex.Attachments.Add(new System.Net.Mail.Attachment("C:\\doc\\start.pdf"));
messagex.BodyEncoding = Encoding.UTF8;
messagex.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.office365.com", 587);
System.Net.NetworkCredential basicCredential1 = new
System.Net.NetworkCredential("noreply#zayzaycorporation.onmicrosoft.com", "XXX");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = basicCredential1;
client.Send(messagex);
context.Done(string.Empty);
The class sends the email with an attachment, works good. But my problem is when it's published as a Web Service in azure because there doesn't find any folder named "doc" on "C:\\". How can it be referenced the attachment to a folder from the main solution?
Thanks.
The Attachment class can be constructed using a Stream, which can thus contain anything and come from anywhere.
So basically generate the attachment in memory and wrap it in a MemoryStream or similar.
Try this..
String path = Application.StartupPath + "\doc\test.xml";
I'm sending an email to people using a template. The problem is that all the tags are being shown.
<p>Hello,</p>
<p> Please, click the following link to change your password </p>
//...
<p> PLEASE DO NOT REPLY TO THIS MESSAGE</p>
The mail received is displaying exactly the original message with all the tags. Is there a way to make it look like
Here's my code:
string path = System.Web.HttpContext.Current.Server.MapPath("~/path/myTemplate.txt");
String body;
using (StreamReader sr = new StreamReader(path))
{
body = sr.ReadToEnd();
}
body = body.Replace("<%PasswordLink%>", pwdLink);
var mail = new MailMessage("from", "to");
mail.Subject = "Password Reset";
mail.Priority = MailPriority.High;
mail.Body = body;
var client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Host = "123.45.67.89";
client.Send(mail);
You need to state that the mail message is HTML. If your using System.Web.Mail.MailMessage then use:
mail.BodyFormat = MailFormat.Html;
If you're using System.Net.Mail.MailMessage then use:
mail.IsBodyHtml = true;
Add mail.IsBodyHtml = true;
This will enable HTML formatting for the email.
I guess you have to define the mail body as HTML:
mail.IsBodyHtml = true;
I have an .Net 4.5 application that sends an email, with an attachment. It works as expected when the email is opened on a desktop, but when opened on a mobile (iPhone in this case) the attachment shows as inline HTML not as an attachment.
When however I forward the same email from my desktop to the phone, the attachment shows up correctly on my phone so I am almost certain that it has to do with how I am specifying mime or content-type, disposition etc. but I can't see what I am doing wrong.
Here is the code - note that
att.ContentType = new System.Net.Mime.ContentType("multipart/mixed");
does create an attachment on iPhone but it is of type = mime-attachment that will not open.
I'm stumped & client awaits - any help greatly appreciated !
private void SendNotice(string body, string attachment, string email, bool pdf = false)
{
MailMessage message = new MailMessage();
message.From = new MailAddress(ConfigurationManager.AppSettings["SMTP.SendFrom"]);
message.Subject = ConfigurationManager.AppSettings["MatchedNoticeSubject"];
message.To.Add(new MailAddress(email));
message.ReplyToList.Add(new MailAddress(ConfigurationManager.AppSettings["SMTP.ReplyTo"]));
message.Body = body;
message.IsBodyHtml = true;
Attachment att = Attachment.CreateAttachmentFromString(attachment, "SeniorInfo.html", System.Text.Encoding.ASCII, "text/html");
//specifying this creates an attachment of type "mime-attachment" that does not open
//att.ContentType = new System.Net.Mime.ContentType("multipart/mixed");
message.Attachments.Add(att);
SmtpClient server = new SmtpClient()
{
EnableSsl = (ConfigurationManager.AppSettings["SMTP.EnableSSL"].ToLower() == "true"),
Host = ConfigurationManager.AppSettings["SMTP.Server"],
Port = Convert.ToInt16(ConfigurationManager.AppSettings["SMTP.Port"]),
Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["SMTP.Account"], ConfigurationManager.AppSettings["SMTP.Password"])
};
server.Send(message);
}
Solved after some trial and error fiddling.
Counter-intuitively the attachment ContentDisposition object is READONLY which lead me to believe that I couldn't meddle in it however the read object is apparently a reference to the actual Attachment.ContentDisposition since setting values on the read instance does (apparently) correct the problem. Also used the Enum for MediaTypeNames (System.Net.Mime.MediaTypeNames.Text.Html) tho I don't think that was the issue.
Email send now looks like this :
private void SendMatchNotice(string body, string attachment, string email, bool pdf = false)
{
MailMessage message = new MailMessage();
message.From = new MailAddress(ConfigurationManager.AppSettings["SMTP.SendFrom"]);
message.Subject = ConfigurationManager.AppSettings["MatchedNoticeSubject"];
message.To.Add(new MailAddress(email));
message.ReplyToList.Add(new MailAddress(ConfigurationManager.AppSettings["SMTP.ReplyTo"]));
message.Body = body;
message.IsBodyHtml = true;
// Create the file attachment for this e-mail message.
Attachment att = Attachment.CreateAttachmentFromString(attachment, "SeniorInfo.html", System.Text.Encoding.ASCII, System.Net.Mime.MediaTypeNames.Text.Html);
System.Net.Mime.ContentDisposition disposition = att.ContentDisposition;
disposition.DispositionType = "attachment";
disposition.Inline = false;
disposition.FileName = "SeniorInfo.html";
disposition.CreationDate = DateTime.Now;
disposition.ModificationDate = DateTime.Now;
disposition.ReadDate = DateTime.Now;
message.Attachments.Add(att);
SmtpClient server = new SmtpClient()
{
EnableSsl = (ConfigurationManager.AppSettings["SMTP.EnableSSL"].ToLower() == "true"),
Host = ConfigurationManager.AppSettings["SMTP.Server"],
Port = Convert.ToInt16(ConfigurationManager.AppSettings["SMTP.Port"]),
Credentials = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["SMTP.Account"], ConfigurationManager.AppSettings["SMTP.Password"])
};
server.Send(message);
}
I have a report created thru an ASP.NET table and I want to send an email message containing this report in the body of the message not as an attachment including the table layout and content. How can this be done in c#? Thank you Dov
I put together the following code from an article at this site http://authors.aspalliance.com/stevesmith/articles/dotnetemailwebsite.asp which I found thru a question asked here "Best way to create complex html email message with asp.net, how?", and from this article How to Print in ASP.NET 2.0 http://www.dotnetcurry.com/ShowArticle.aspx?ID=92.
I use an asp.net panel so that I can get only parts of the page and not the whole page so that you can send a table, in my case, without having to send the button which activates sending the email or any other part of the page which I don't want to send.
NOTE: Any style properties for controls sent must be set directly to the controls and not thru cssclass.
This is the code:
//Here I extract html of the control to be sent
StringWriter stringWrite = new StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
//pnlRpt is an asp.net panel containing the controls to be sent
pnlRpt.RenderControl(htmlWrite);
string htmlStr = stringWrite.ToString();
//Here I send the message whith the html of the table
MailMessage msg = new MailMessage();
msg.From = new MailAddress("EmailOfSender");
msg.To.Add("emailOfReceiver");
msg.Subject = "your subject";
msg.Body = htmlStr;
msg.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient(mailServer);
smtp.Credentials = new System.Net.NetworkCredential(userName, usePass);
smtp.Send(msg);
msg.Dispose();
With this code I sent an asp.net table generated and populated in background code and it worked perfectly.
You can make http request to asp.net page then, you can embed the response in body of mail.
You should set mail Body format as html.
You can send HTML email in .NET using System.Mail.Net
Something like
//create the mail message
MailMessage mail = new MailMessage();
//set the addresses
mail.From = new MailAddress("me#mycompany.com");
mail.To.Add("you#yourcompany.com");
//set the content
mail.Subject = "This is an email";
mail.Body = "this is a sample body with html in it. <b>This is bold</b> <font color=#336699>This is blue</font>";
mail.IsBodyHtml = true;
//send the message
SmtpClient smtp = new SmtpClient("address of email server possibly localhost");
smtp.Send(mail);
Notice the body is HTML so you can include a table. Be careful with formatting though different email clients support different amounts of HTML and it is best to keep things simple.
Try below code snippet
protected void SendEmail(object sender, EventArgs e)
{
try
{
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
// GridView5.DataBind();
GridView5.RenderControl(hw);//this is my gridview name
StringReader sr = new StringReader(sw.ToString());
MailMessage mm = new MailMessage("gowdhaman92#gmail.com", "gowdhaman92#gmail.com");//From and To Mail id's
mm.Subject = "Quotation from INDIAN Departmental store,Udumalpet";
mm.Body = "INDIAN Departmental store,Udumalpet:<hr />" + sw.ToString();
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = "gowdhaman92#gmail.com";
NetworkCred.Password = "perumalpudur";
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Alert message", "alert('mail sent');", true);
}
}
}
catch (Exception)
{
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Mail not sent!!!');", true);
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}