2009-07-11 12 views
15

el envío de correo junto con la imagen incrustada utilizando asp.netde envío de correo, junto con imagen incrustada utilizando asp.net

ya he utilizado siguiente, pero que no puede trabajar

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) 

Respuesta

29

Si está utilizando. NET 2 o superior puede utilizar la AlternateView y clases LinkedResource así:

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

Esperemos que se puede deducir la VB equivalente.

+2

Golpeado por un hombre con el mismo nombre. –

+1

Ocurre a veces;) – Alex

+6

ser golpeado es mejor que conseguir que tus ojos se penetren, lo adivinaría –

8

Después de buscar e intentar debe haber cuatro o cinco "respuestas", sentí que tenía que compartir lo que finalmente encontré para trabajar ya que muchas personas parecen no saber cómo hacer esto o algunos dan respuestas elaboradas que tantos otros tiene problemas con, más algunos lo hacen y solo dan una respuesta de fragmento que luego debe ser interpretada. Como no tengo un blog pero me gustaría ayudar a otros, aquí hay un código completo para hacerlo todo. Muchas gracias a Alex Peck, ya que es su respuesta expandida.

archivo inMy.aspx asp.net

<div> 
    <asp:LinkButton ID="emailTestLnkBtn" runat="server" OnClick="sendHTMLEmail">testemail</asp:LinkButton> 
</div> 

código inMy.aspx.cs detrás de C# archivo

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 = "[email protected]"; // 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("[email protected]", "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> 

en su archivo Web.config , dentro de tu bloque de configuración <> necesitas lo siguiente para permitir la prueba en una carpeta TempMail en tu c: \ dri ve

<system.net> 
    <mailSettings> 
     <smtp deliveryMethod="SpecifiedPickupDirectory" from="[email protected]"> 
      <specifiedPickupDirectory pickupDirectoryLocation="C:\TempMail"/> 
     </smtp> 
    </mailSettings> 
</system.net> 

las únicas otras cosas que va a necesitar en la parte superior de sus aspx.cs código detrás de archivo son de un sistema mediante incluye (si me he perdido uno se hace clic justo en la clase desconocida y elegir el opción de 'resolver')

using System.Net.Mail; 
using System.Text; 
using System.Reflection; 
using System.Net.Mime; // need for mail message and text encoding 
using System.IO; 

esperanza esto ayuda a alguien y muchas gracias al cartel de arriba para dar la respuesta necesaria para realizar el trabajo (así como el otro enlace en mi código).

Funciona, pero estoy abierto a mejoras.

aplausos.

Cuestiones relacionadas