Invia immagine in linea nell’e-mail

Avere un problema nell’invio di un’immagine via email come immagine incorporata nel corpo. Il file di immagine viene mostrato come allegato, ma la porzione di immagine in linea viene semplicemente visualizzata come una x rossa.

Ecco cosa ho finora

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

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

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

Prova questo

  string htmlBody = "

Picture


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

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

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

Il codice c # minimo per incorporare un’immagine può essere:

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

Prova questo.


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

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

È necessario aggiungere LinkedResource in un AlternateView

 AlternateView alternateView = AlternateView.CreateAlternateViewFromString("

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

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

Un esempio ancora più minimalista:

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

Oltre ai commenti sopra, ho i seguenti commenti aggiuntivi:

  • Non mischiare Allegati e AlternativeView, l’uso o l’altro. Se li mescoli, gli allegati inline verranno renderizzati come download sconosciuti.
  • Mentre Outlook e Google consentono lo stile HTML standard "cid:att-001" questo NON funziona su iPhone (livello patch tardivo del 2016), piuttosto usa puro alfa numerico "cid:att-001" -> "cid:att001"

Per inciso. Il rendering di Outlook (anche di Office 2015) (ancora la netta maggioranza per gli utenti di bussiness) richiede l’uso di HTML in stile TABLE TR TD perché non supporta completamente il modello di box HTML.

L’altra soluzione è albind l’immagine come allegato e quindi fare riferimento al codice html utilizzando cid. Codice HTML:

        

Codice C #:

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

invio di 2 immagini codice vb.net convertito per convertitore online C #.

 Public Function SendEmail(Optional ByVal p_AsHTML As Boolean = False, Optional ByVal p_themEmail As String = "") 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 String In _To aMessage.To.Add(New MailAddress(anAdd)) Next For Each cc As String In _CC aMessage.CC.Add(New MailAddress(cc)) Next For Each bcc As String 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.ToString().ToLower.Contains("dexus") Then Dim htmlView = AlternateView.CreateAlternateViewFromString(_Body.ToString(), 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.CreateAlternateViewFromString(_Body.ToString(), 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 String = "" Dim DexuslogoImage1 As String = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images\Dexus_Notice_Logo.png") Dim DexuslogoImage2 As String = 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.ToString("dd/MM/yyyy") + "

" bodys += "
" bodys += "

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

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

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

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