Here is a situation.
I am sending an email that has image as html body
<img src="http://www.google.com/images/srpr/logo11w.png" alt="click me" />
After receiving email image src is changed to
<img src="https://bay179.mail.live.com/Handlers/ImageProxy.mvc?bicild=&canary=ei12UmVJE9u9hgMk5TdV12Y1X%2b9Vc365IL%2bmULwd%2bfk%3d0&url=http%3a%2f%2fwww.google.com%2fimages%2fsrpr%2flogo11w.pngf" alt="click me">
Hence does not render image. Following is the code used to send email
SmtpClient sc = new SmtpClient("smtp.live.com");
sc.Port = 587;
sc.UseDefaultCredentials = false;
sc.Credentials = new NetworkCredential("someemail#hotmail.com", "password");
sc.EnableSsl = true;
MailMessage m = new MailMessage();
m.From = new MailAddress("someemail#hotmail.com");
m.Subject = "test subject";
m.IsBodyHtml = true;
m.Body = "<img src=\"http://www.google.com/images/srpr/logo11w.png\" alt=\"click me\" /><img src=\"https://campaign-uploads.s3.amazonaws.com/newsletter/2015/19Apr_wk17/EN/images/logo.jpg\" />";
m.To.Add(new MailAddress("someemail#hotmail.com"));
sc.Send(m);
First image url gets changed and second image's url remains same. So whats the science?
I don't want to embed image.
Once you send the e-mail you have yielded control to the receiving system. Most MTAs are going to do some kind of reformatting either due to anti-virus, phishing, etc. scans. Many will rework the img source to use their own proxies. You have no way to stop them. You just get to work with them.
Related
I am generating QR code in c# using the qrcoder library. I can generate the code with the information i want, but i would like to send it also through email.
Using following code i get the email, but it won't display the image of the QR code in it. And if I change the address in which I think the code its being saved it also give an error like this:
System.Runtime.InteropServices.ExternalException occurred A generic error occurred in GDI+.
Here is the code:
public void GenerateQR(string infoReserva)
{
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeData qrCodeData = qrGenerator.CreateQrCode(infoReserva, QRCodeGenerator.ECCLevel.Q);
QRCode qrCode = new QRCode(qrCodeData);
using (Bitmap bitMap = qrCode.GetGraphic(20))
{
bitMap.Save(Server.MapPath("~/Images/qrcode.png"), ImageFormat.Png);
}
MailMessage mm = new MailMessage();
mm.From = new MailAddress("name#exampple.comr");
mm.Subject = "How to email self-generated QR code";
mm.Body = " <html><body> <p> QR code as below</p> <p> <img src='http://localhost:44362//Images/qrcode.png' alt='QR Code'/></p> </body></html> ";
mm.To.Add("name#exampple.com");
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential();
NetworkCred.UserName = "name#exampple.comr";
NetworkCred.Password = "-----";
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
}
I have the code of my project organized in folder like this:
1_Entites
2_DataAcces
3_Exceptions
4_API
5_WEBAPP
The first 4 folder are the backend of the aplications, and the folder named WebApp is in which i have this code and the front end of the app, in this folder i created the folder of Images
Do you know what is the best way of sending this email with de qr code
Thanks in advance!
You’re still going to struggle no matter what you do because you’re trying to send an image and somewhere there will be a mail client that blocks it (linking to an image on your server is a classic spammer trick and nearly certain to be blocked, gmail blocks images sent as data url but accepts inline attached multipart, somewhere else you’ll find a device, probably a phone, that doesn’t accept multipart embedded but accepts data urls..); I’d ditch the idea of sending any graphical pictures at all in the email and switch to using a QR library that can output characters or html so you can form your QR using blocks of black and white (characters or html elements). Not an endorsement and no affiliation, but I know QRCoder can output character based QRs
In the HTML there are two images:
<IMG SRC="cid:#IMG01#" >
<IMG SRC="cid:#IMG02#" >
The C# code is:
var message = new MailMessage
{
Priority = MailPriority.Normal,
Sender = new MailAddress(utente.Email, "xxx.it"),
From = new MailAddress(utente.Email, "xxx.it")
};
message.To.Add(new MailAddress("xxx#tiscali.it", "aaaaaaaa"));
message.Subject = "xywz";
message.IsBodyHtml = true;
message.Body = Modello;
Attachment AttPrinc = new Attachment(path + "Attachment.pdf");
message.Attachments.Add(AttPrinc);
string contentID1 = "IMMAGINE01";
string contentID2 = "IMMAGINE02";
Modello = Modello.Replace("#IMG01#", contentID1);
Modello = Modello.Replace("#IMG02#", contentID2);
LinkedResource InlineImg01 = new LinkedResource(path + "img01.jpg", "image/jpg");
InlineImg01.ContentId = contentID1;
LinkedResource InlineImg02 = new LinkedResource(path + "img02.jpg", "image/jpg");
InlineImg02.ContentId = contentID2;
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(Modello, null, "text/html");
htmlView.LinkedResources.Add(InlineImg02);
htmlView.LinkedResources.Add(InlineImg01);
message.AlternateViews.Add(htmlView);
var mailClient = new SmtpClient();
mailClient.Send(message);
I send the email and, on my PC with Thunderbird, I see all correct, on my PC with the webmail, I see the images, on my phone (Huawey Mate 8) with webmail, I don't see the images.
I send the email to other persons (tester), and some of them can see the images, some others can't see the images.
I'm going crazy.
Any suggestion?
After long hours of debug, I found the problem: the HTML file was generated by Word ... I rewrote the file from scratch and magically all works well everywhere.
The HTML code generated by Word was something insane, classes and classes, all for a simple document.
sending mail along with embedded image using asp.net
I have already used following but it can't work
Dim EM As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage(txtFrom.Text, txtTo.Text)
Dim A As System.Net.Mail.Attachment = New System.Net.Mail.Attachment(txtImagePath.Text)
Dim RGen As Random = New Random()
A.ContentId = RGen.Next(100000, 9999999).ToString()
EM.Attachments.Add(A)
EM.Subject = txtSubject.Text
EM.Body = "<body>" + txtBody.Text + "<br><img src='cid:" + A.ContentId +"'></body>"
EM.IsBodyHtml = True
Dim SC As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient(txtSMTPServer.Text)
SC.Send(EM)
If you are using .NET 2 or above you can use the AlternateView and LinkedResource classes like this:
string html = #"<html><body><img src=""cid:YourPictureId""></body></html>";
AlternateView altView = AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html);
LinkedResource yourPictureRes = new LinkedResource("yourPicture.jpg", MediaTypeNames.Image.Jpeg);
yourPictureRes.ContentId = "YourPictureId";
altView.LinkedResources.Add(yourPictureRes);
MailMessage mail = new MailMessage();
mail.AlternateViews.Add(altView);
Hopefully you can deduce the VB equivalent.
After searching and trying must be four or five 'answers' I felt I had to share what I finally found to actually work as so many people seem to not know how to do this or some give elaborate answers that so many others have issues with, plus a few do and only give a snippet answer which then has to be interpreted. As I don't have a blog but I'd like to help others here is some full code to do it all. Big thanks to Alex Peck, as it's his answer expanded on.
inMy.aspx asp.net file
<div>
<asp:LinkButton ID="emailTestLnkBtn" runat="server" OnClick="sendHTMLEmail">testemail</asp:LinkButton>
</div>
inMy.aspx.cs code behind c# file
protected void sendHTMLEmail(object s, EventArgs e)
{
/* adapted from http://stackoverflow.com/questions/1113345/sending-mail-along-with-embedded-image-using-asp-net
and http://stackoverflow.com/questions/886728/generating-html-email-body-in-c-sharp */
string myTestReceivingEmail = "yourEmail#address.com"; // your Email address for testing or the person who you are sending the text to.
string subject = "This is the subject line";
string firstName = "John";
string mobileNo = "07711 111111";
// Create the message.
var from = new MailAddress("emailFrom#address.co.uk", "displayed from Name");
var to = new MailAddress(myTestReceivingEmail, "person emailing to's displayed Name");
var mail = new MailMessage(from, to);
mail.Subject = subject;
// Perform replacements on the HTML file (which you're using as a template).
var reader = new StreamReader(#"c:\Temp\HTMLfile.htm");
string body = reader.ReadToEnd().Replace("%TEMPLATE_TOKEN1%", firstName).Replace("%TEMPLATE_TOKEN2%", mobileNo); // and so on as needed...
// replaced this line with imported reader so can use a templete ....
//string html = body; //"<html><body>Text here <br/>- picture here <br /><br /><img src=""cid:SACP_logo_sml.jpg""></body></html>";
// Create an alternate view and add it to the email. Can implement an if statement to decide which view to add //
AlternateView altView = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
// Logo 1 //
string imageSource = (Server.MapPath("") + "\\logo_sml.jpg");
LinkedResource PictureRes = new LinkedResource(imageSource, MediaTypeNames.Image.Jpeg);
PictureRes.ContentId = "logo_sml.jpg";
altView.LinkedResources.Add(PictureRes);
// Logo 2 //
string imageSource2 = (Server.MapPath("") + "\\booking_btn.jpg");
LinkedResource PictureRes2 = new LinkedResource(imageSource2, MediaTypeNames.Image.Jpeg);
PictureRes2.ContentId = "booking_btn.jpg";
altView.LinkedResources.Add(PictureRes2);
mail.AlternateViews.Add(altView);
// Send the email (using Web.Config file to store email Network link, etc.)
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.Send(mail);
}
HTMLfile.htm
<html>
<body>
<img src="cid:logo_sml.jpg">
<br />
Hi %TEMPLATE_TOKEN1% .
<br />
<br/>
Your mobile no is %TEMPLATE_TOKEN2%
<br />
<br />
<img src="cid:booking_btn.jpg">
</body>
</html>
in your Web.Config file, inside your < configuration > block you need the following to allow testing in a TempMail folder on your c:\drive
<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory" from="madeupEmail#address.com">
<specifiedPickupDirectory pickupDirectoryLocation="C:\TempMail"/>
</smtp>
</mailSettings>
</system.net>
the only other things you will need at the top of your aspx.cs code behind file are the Using System includes (if I've missed one out you just right click on the unknown class and choose the 'Resolve' option)
using System.Net.Mail;
using System.Text;
using System.Reflection;
using System.Net.Mime; // need for mail message and text encoding
using System.IO;
Hope this helps someone and big thanks to the above poster for giving the answer needed to get the job done (as well as the other link in my code).
It works but im open to improvements.
cheers.
Thanks to the other answers I managed to get this to work - the only difference is the directory of the image - if the image is the same directory as the application than this can be used Ex:Directory.GetCurrentDirectory() + #"\ClientApp\public\img\blur.jpg
public void SendMail(string receiver, string subject, string content)
{
SmtpClient client = new SmtpClient(emailServiceConfig.SmtpServer);
client.EnableSsl = true; // Important ###
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(emailServiceConfig.Username, emailServiceConfig.Password);
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(emailServiceConfig.From);
mailMessage.To.Add(receiver);
//mailMessage.Body = content;
mailMessage.Subject = subject;
//Adding image =============================================
string html = #$"<html><body><img src=""cid:PageScreenshot"">{content}</body></html>";
AlternateView altView = AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html);
LinkedResource screenshotRes = new LinkedResource(Directory.GetCurrentDirectory() + #"\ClientApp\public\img\screeenshot2.jpg", MediaTypeNames.Image.Jpeg);
screenshotRes.ContentId = "PageScreenshot";
altView.LinkedResources.Add(screenshotRes);
mailMessage.AlternateViews.Add(altView);
client.Send(mailMessage);
}
to specify the question:
I'm creating a bitmap object, which I want to send with an email. I don't want to save it before or upload it to a webserver. Just attach it and then link the attachement in the html body of the mail.
I've searched quite a time now and all I can find are answers in which the picture is stored in the file system or on a server.
So is there any way to do this whithout saving the image before?
Thanks
Edit:
I've tried around a bit and finally came to this solution:
MailMessage mail = new MailMessage();
mail.To.Add(new MailAddress("xxx#yyy.de"));
mail.From = new MailAddress("xxx#yyy.de");
SmtpClient sender = new SmtpClient
{
Host = "smtp.client",
Port = 25
};
mail.Subject = "test";
body= "blablabla<br><img alt=\"\" hspace=0 src=\"cid:ImagedId\" align=baseline border=0 ><br>blablabla";
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");
using (System.IO.MemoryStream image = new System.IO.MemoryStream())
{
Bitmap diagram = new Bitmap("C:\\qwer.bmp");
diagram.Save(image, System.Drawing.Imaging.ImageFormat.Jpeg);
LinkedResource resource = new LinkedResource(image, "image/jpeg");
resource.ContentId = "ImageId";
resource.TransferEncoding = System.Net.Mime.TransferEncoding.Base64;
htmlView.LinkedResources.Add(resource);
mail.AlternateViews.Add(htmlView);
sender.Send(mail);
}
But now my MailClient (Lotus Notes) doesnt open the mail with the error: "no mime data".
Any Idea how to solve this?
Try creating it in Word (either just the image or whole email) then drag over it and copy and paste into Outlook. I think that auto attaches images as well as embeds them.
I would like to send mail with a picture inside the email body. In my first attempts, the picture appears like an attachment: it is visible but at the end. I need the picture to be at the center of the email body.
The tutorial which I used is link.
My code looks like this:
mail.Body = "string htmlBody = \"<html><body><h1><center><img src=\"C:\\picture.png\"/></h1></html>";
string contentID = "image1";
Attachment inline = new Attachment("C:\\picture.png");
inline.ContentDisposition.Inline = true;
inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline;
inline.ContentId = contentID;
inline.ContentType.MediaType = "image/png";
inline.ContentType.Name = "C:\\picture.png";
mail.Attachments.Add(inline);
mail.IsBodyHtml = true;
If you'd really have followed the tutorial, you'd have seen this code:
email.Body = "[...]<img src=\"##IMAGE##\" alt=\"\">";
// generate the contentID string using the datetime
string contentID = Path.GetFileName(attachmentPath).Replace(".", "");
Attachment inline
[...]
inline.ContentId = contentID;
[...]
email.Attachments.Add(inline);
// replace the tag with the correct content ID
email.Body = email.Body.Replace("##IMAGE##", "cid:" + contentID);
Of course using <img src="C:\picture.png"> won't work, since the user that receives the mail most probably won't have that image in that path on their PC, let alone when they're using webmail.