The image is not displayed when sent to email - c#

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.

Related

Changing the position of an image in E-mail using C# WinForms

I use the following code to send an email along with an image, the image is not an attachment its simply used to add more detail to the email instead of it being just plain text:
private void button1_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
mail.To.Add(jTextBox1.TextValue);
mail.From = new MailAddress("E-mail");
mail.Subject = "Re, Passport admission";
mail.IsBodyHtml = true;
var inlineLogo = new LinkedResource(#"C:\Users\Lenovo\Desktop\c# pictures\eagle.png", "image/png");
inlineLogo.ContentId = Guid.NewGuid().ToString();
string body = string.Format(#"<img src=""cid:{0}"" /> <p>Lorum Ipsum Blah Blah</p><p>Lorum Ipsum Blah Blah</p>", inlineLogo.ContentId);
var view = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
view.LinkedResources.Add(inlineLogo);
mail.AlternateViews.Add(view);
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
//has to be a valid email address
smtp.Credentials = new System.Net.NetworkCredential("E-mail", "Password");
smtp.Send(mail);
MessageBox.Show("your email has been sent");
}
This code works perfectly but i want to change the position of the image in the Email to the middle, right now its to the left. Is there a way to change the position?

I want to email the screenshot in tabular format stored in my local using C#?

I want to automate my work by sending the screenshot taken during automation in tabular email format . I had successfully attached as document, but I want it in tabular format. This is code what I had already tried
public static void email_send() {
string htmlBody = "<html><body><h1>Picture</h1><br><img src=\"cid:test1.jpeg\"></body></html>";
AlternateView avHtml = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
LinkedResource inline = new LinkedResource("test1.jpeg", MediaTypeNames.Image.Jpeg);
inline.ContentId = Guid.NewGuid().ToString();
avHtml.LinkedResources.Add(inline);
Attachment att = new Attachment(#"D:/test123.png");
att.ContentDisposition.Inline = true;
MailMessage mail = new MailMessage();
mail.AlternateViews.Add(avHtml);
System.Net.Mail.SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("*****");
mail.To.Add("*******");
mail.Subject = "Test Mail - 1";
mail.Body = String.Format(
"<h3>Client: " + " Has Sent You A Screenshot</h3>" +
#"<img src=""cid:{0}"" />", inline.ContentId);
mail.IsBodyHtml = true;
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("******", "******");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
You have missed the attachment.
Your linked resource also needs to be attached to the email. You need to add the following code:
mail.Attachments.Add(att);

Email sent still contains HTML tags.

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;

Asp.Net Email Attachment Displaying Inline on Mobile (iPhone)

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

How can I send an ASP.NET table as an Email message not as an attachment?

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 */
}

Categories

Resources