Envoyer une image en ligne par email

Avoir un problème lors de l’envoi d’une image par courrier électronique en tant qu’image intégrée dans le corps. Le fichier image se présente sous la forme d’une pièce jointe, ce qui est correct, mais la partie image en ligne est simplement affichée en rouge.

Voici ce que j’ai jusqu’ici

LinkedResource inline = new LinkedResource(filePath); inline.ContentId = Guid.NewGuid().ToSsortingng(); 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 = Ssortingng.Format( "

Client: " + data.client_id + " Has Sent You A Screenshot

" + @"", inline.ContentId); mail.IsBodyHtml = true; mail.Attachments.Add(att);

Essaye ça

  ssortingng htmlBody = "

Picture


"; AlternateView avHtml = AlternateView.CreateAlternateViewFromSsortingng (htmlBody, null, MediaTypeNames.Text.Html); LinkedResource inline = new LinkedResource("filename.jpg", MediaTypeNames.Image.Jpeg); inline.ContentId = Guid.NewGuid().ToSsortingng(); 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 = Ssortingng.Format( "

Client: " + data.client_id + " Has Sent You A Screenshot

" + @"", inline.ContentId); mail.IsBodyHtml = true; mail.Attachments.Add(att);

Le code c # minimal pour intégrer une image peut être:

 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(Ssortingng filePath) { LinkedResource res = new LinkedResource(filePath); res.ContentId = Guid.NewGuid().ToSsortingng(); ssortingng htmlBody = @""; AlternateView alternateView = AlternateView.CreateAlternateViewFromSsortingng(htmlBody, null, MediaTypeNames.Text.Html); alternateView.LinkedResources.Add(res); return alternateView; } 
  protected void Page_Load(object sender, EventArgs e) { ssortingng Themessage = @"  
Hi!
"; sendHtmlEmail("from@gmail.com", "tomailaccount", Themessage, "Scoutfoto", "Test HTML Email", "smtp.gmail.com", 25); } protected void sendHtmlEmail(ssortingng from_Email, ssortingng to_Email, ssortingng body, ssortingng from_Name, ssortingng Subject, ssortingng 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.CreateAlternateViewFromSsortingng(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); }

Essaye ça.


 protected void Page_Load(object sender, EventArgs e) { ssortingng Themessage = @"  
Hi!
"; sendHtmlEmail("from@gmail.com", "tomailaccount", Themessage, "Scoutfoto", "Test HTML Email", "smtp.gmail.com", 25); }

 protected void sendHtmlEmail(ssortingng from_Email, ssortingng to_Email, ssortingng body, ssortingng from_Name, ssortingng Subject, ssortingng 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.CreateAlternateViewFromSsortingng(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); } 

Vous devez append le LinkedResource dans un AlternateView

 AlternateView alternateView = AlternateView.CreateAlternateViewFromSsortingng("

Client: " + data.client_id + " Has Sent You A Screenshot

" + @"", null, "text/html"); alternateView.LinkedResources.Add(inline); mail.AlternateViews.Add(alternateView);

Un exemple encore plus minimaliste:

 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"; var alternateView = AlternateView.CreateAlternateViewFromSsortingng(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); 
  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 ssortingng plainText = "Non-HTML Plain Text Message for Non-HTML enable mode"; AlternateView plainView = AlternateView.CreateAlternateViewFromSsortingng(plainText, null, "text/plain"); XmlTextReader reader = new XmlTextReader(@"E:\HTMLPage.htm"); ssortingng[] address = new ssortingng[30]; ssortingng finalHtml = ""; var i = -1; while (reader.Read()) { if (reader.NodeType == XmlNodeType.Element) { // The node is an element. if (reader.AtsortingbuteCount <= 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 += ""; } } AlternateView htmlView = AlternateView.CreateAlternateViewFromSsortingng(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); } 

En plus des commentaires ci-dessus, j’ai les commentaires supplémentaires suivants:

  • Ne mélangez pas les pièces jointes et AlternativeView, l’utilisation de ou l’autre. Si vous les mélangez, les pièces jointes intégrées seront affichées sous forme de téléchargements inconnus.
  • Alors qu’Outlook et Google autorisent un style HTML standard, "cid:att-001" ne fonctionne PAS sur l’iPhone (niveau des correctifs de la fin 2016), mais utilise plutôt de l’alpha numérique "cid:att-001" -> "cid:att001"

En aparté. Outlook (même Office 2015) rend le rendu (encore la majorité claire pour les utilisateurs de bussiness) qui nécessite l’utilisation du style HTML de type TABLE TR TD car il ne prend pas totalement en charge le modèle de boîte HTML.

L’autre solution consiste à attacher l’image en pièce jointe, puis à lui référencer le code HTML à l’aide de cid. Code HTML:

        

Code C #:

 EmailMessage email = new EmailMessage(service); email.Subject = "Email with Image"; email.Body = new MessageBody(BodyType.HTML, html); email.ToRecipients.Add("abc@xyz.com"); ssortingng 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(); 

envoi de 2 images conversion de code vb.net pour le convertisseur en ligne C #.

 Public Function SendEmail(Optional ByVal p_AsHTML As Boolean = False, Optional ByVal p_themEmail As Ssortingng = "") 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 Ssortingng In _To aMessage.To.Add(New MailAddress(anAdd)) Next For Each cc As Ssortingng In _CC aMessage.CC.Add(New MailAddress(cc)) Next For Each bcc As Ssortingng 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.ToSsortingng().ToLower.Contains("dexus") Then Dim htmlView = AlternateView.CreateAlternateViewFromSsortingng(_Body.ToSsortingng(), 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.CreateAlternateViewFromSsortingng(_Body.ToSsortingng(), 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 Ssortingng = "" Dim DexuslogoImage1 As Ssortingng = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images\Dexus_Notice_Logo.png") Dim DexuslogoImage2 As Ssortingng = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images\DexusTenantNotice.png") passwordlink = "here.
" bodys += "
" bodys += " " 'edit bodys += "

Your Dexus Response Password is about to expire

" + DateTime.Now.ToSsortingng("dd/MM/yyyy") + "

" bodys += "
" bodys += "

" + wishes + " " + p_TenantName.Trim().ToSsortingng() + "

" bodys += "
" bodys += "Your Dexus Response password is about to expire in " + p_remaindays.ToSsortingng() + " days.

To reset your password and update your details, please click " + passwordlink.ToSsortingng() + "

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.Please contact Dexus Response if you require assistance in accessing the portal.

Dexus Response

property.services@dexusfm.com | 1300 339 870 | response.dexus.com