Why image is not displaying in html mail in gmail? - c#

I'm trying to add an image in HTML mail. It is displaying when I save that body as html file, but when I send that html body as an email through GMail, the image is not displaying. Can anyone tell me the reason?
I set the source of the image in this way:
var image = body.GetElementsByTagName("img");
string imageAttachmentPath = Path.Combine(Globals.NotificationTemplatesPath, "Header.png");
foreach (XmlElement img in image)
{
img.SetAttribute("src", imageAttachmentPath);
break;
}
//thats the method in which i am sending email.
public static void SendMessageViaEmailService(string from,
string sendTo,
string carbonCopy,
string blindCarbonCopy,
string subject,
string body,
bool isBodyHtml,
string imageAttachmentPath,
Hashtable images,
List<string> attachment,
string title = null,
string embeddedImages = null)
{
Attachment image = new Attachment(imageAttachmentPath);
MailMessage msg = new MailMessage();
msg.IsBodyHtml = true; // email body will allow html elements
msg.From = new MailAddress(from, "Admin"); // setting the Sender Email ID
msg.To.Add(sendTo); // adding the Recipient Email ID
if (!string.IsNullOrEmpty(carbonCopy)) // add CC email ids if supplied.
msg.CC.Add(carbonCopy);
msg.Subject = subject; //setting email subject and body
msg.Body = body;
msg.Attachments.Add(image);
//create a Smtp Mail which will automatically get the smtp server details
//from web.config mailSettings section
SmtpClient SmtpMail = new SmtpClient();
SmtpMail.Host = "smtp.gmail.com";
SmtpMail.Port = 587;
SmtpMail.EnableSsl = true;
SmtpMail.UseDefaultCredentials = false;
SmtpMail.Credentials = new System.Net.NetworkCredential(from, "password");
// sending the message.
try
{
SmtpMail.Send(msg);
}
catch (Exception ex) { }
}

More than likely your image SRC attribute is not an absolute, publicly-accessible URI. Any file-system or local URI's will not show the image in the email.
Specifically, these will not work:
c://test.png
test.png
/folder/test.png
http://localhost/test.png
http://internaldomain/test.png
Ensure that your image urls are
absolute (i.e. start with the protocol like http://)
includes a full path to the image
the domain is a public domain

Try the code part from this thread:
// creating the attachment
System.Net.Mail.Attachment inline = new System.Net.Mail.Attachment(#"c:\\test.png");
inline.ContentDisposition.Inline = true;
// sending the message
MailMessage email = new MailMessage();
// set the information of the message (subject, body ecc...)
// send the message
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("localhost");
smtp.Send(email);
email.Dispose();

Related

The image is not displayed when sent to email

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.

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

insert a link in to a email send using c#

I develop a program to send emails automatically using c#, and I want to insert a link to a web site to that email. How can I do it?
public bool genarateEmail(String from, String to, String cc, String displayName,
String password, String subjet, String body)
{
bool EmailIsSent = false;
MailMessage m = new MailMessage();
SmtpClient sc = new SmtpClient();
try
{
m.From = new MailAddress(from, displayName);
m.To.Add(new MailAddress(to, displayName));
m.CC.Add(new MailAddress("xxx#gmail.com", "Display name CC"));
m.Subject = subjet;
m.IsBodyHtml = true;
m.Body = body;
sc.Host = "smtp.gmail.com";
sc.Port = 587;
sc.Credentials = new
System.Net.NetworkCredential(from, password);
sc.EnableSsl = true;
sc.Send(m);
EmailIsSent = true;
}
catch (Exception ex)
{
EmailIsSent = false;
}
return EmailIsSent;
}
I want to send a link through this email. How should I add it to email?
You should be able to just add the mark-up for the link in your body variable:
body = "blah blah <a href='http://www.example.com'>blah</a>";
You shouldn't have to do anything special since you're specifying your body contains HTML (m.IsBodyHtml = true).
String body = "Your message : <a href='http://www.example.com'></a>"
m.Body = body;
Within the body. This will require that the body be constructed as HTML so the that a or can be used to render your link. You can use something like StringTemplate to generate the html including your link.
For some dynamic links, the email service providers will not show your link into email body if the link not prepend http (security issues)
like localhost:xxxx/myPage
m.body = "<a href='http://" + Request.Url.Authority + "/myPage'>click here</a>"

Email From ASP.net is going as HTML attachment

As the title says, I am sending email from my ASP.net web application without any attachment (for now) but strangely the body of email is going as a separate HTML file attached to blank email like when I click the HTML file it opens the body in separate window with everything that I have written in body as standalone HTML file, this is only happening when I send email to some portals like e-lance but when I send it to gmail or hotmail address then email is going perfectly with no attachment and body-text appearing where it should.
My email code is
public bool sendMail(string messageSubject, System.Net.Mail.MailAddress fromEmailAddress, System.Net.Mail.MailAddress toEmailAddress, string source_id, string messageText)
{
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.IsBodyHtml = true;
mail.Subject = messageSubject;
mail.From = fromEmailAddress;
mail.To.Add(toEmailAddress);
mail.Body = messageText;
SmtpClient relayServer = new SmtpClient();
List<KeyValuePair<string, string>> commandParameters = new List<KeyValuePair<string,string>>();
commandParameters.Add(new KeyValuePair<string,string>("#source_id", source_id));
DataTable sourcesTable = SQLSelect("SELECT * FROM LogiCrmSources WHERE source_id = #source_id", commandParameters);
relayServer.Host = sourcesTable.Rows[0]["source_smtp"].ToString();
relayServer.Port = Convert.ToInt16(sourcesTable.Rows[0]["source_smtp_port"].ToString());
if (relayServer.Port == 25)
{
relayServer.EnableSsl = false;
}
else
{
relayServer.EnableSsl = true;
}
relayServer.Credentials = new System.Net.NetworkCredential(sourcesTable.Rows[0]["source_email"].ToString(), sourcesTable.Rows[0]["source_password"].ToString());
try
{
relayServer.Send(mail);
return true;
}
catch(SmtpFailedRecipientException exp)
{
return false;
}
}
Not all clients can handle html emails properly. Gmail for example can while the portals you mention can't. In those cases the body of the email as sent as an attachment.

opennetcf.net.mail attachment help

Thanks for looking at my question.
I am trying to figure out attachments for OpenNetCF.Net.Mail. Here is the code for my SendMail function:
public static void SendMessage(string subject,
string messageBody,
string fromAddress,
string toAddress,
string ccAddress)
{
MailMessage message = new MailMessage();
SmtpClient client = new SmtpClient();
MailAddress address = new MailAddress(fromAddress);
// Set the sender's address
message.From = address;
// Allow multiple "To" addresses to be separated by a semi-colon
if (toAddress.Trim().Length > 0)
{
foreach (string addr in toAddress.Split(';'))
{
message.To.Add(new MailAddress(addr));
}
}
// Allow multiple "Cc" addresses to be separated by a semi-colon
if (ccAddress.Trim().Length > 0)
{
foreach (string addr in ccAddress.Split(';'))
{
message.CC.Add(new MailAddress(addr));
}
}
// Set the subject and message body text
message.Subject = subject;
message.Body = messageBody;
// TODO: *** Modify for your SMTP server ***
// Set the SMTP server to be used to send the message
client.Host = "smtp.dscarwash.com";
string domain = "dscarwash.com";
client.Credentials = new SmtpCredential("mailuser", "dscarwash10", domain);
// Send the e-mail message
try
{
client.Send(message);
}
catch (Exception e)
{
string data = e.ToString();
}
}
It is supposed to be a matter of tweaking it in the following way to allow attachments:
Attachment myAttachment = new Attachment();
message.Attachments.Add(myAttachment);
The problem is that I cannot figure out how to get the attachment to add. The lines above should be it with something else in the middle where I actually tell it what file I would like to attach. Any help on this matter will be greatly appreciated.
Thanks again!
As per this MSDN documentation, you can specify the filename of the attachment as a parameter. Thus, you can give the fullpath as the string parameter.
They have AttachmentBase which can be used to construct a email attachment. However, we cannot add the instance of AttachmentBase to the attachments of email message.
I think the Attachment class should inherit from AttachmentBase. I think this maybe a defect.

Categories

Resources