2014-02-07 3 views
0

나는 로컬 dev 컴퓨터에서 이미지와 함께 테스트 이메일을 보내려고합니다. 이미지가 첨부 파일로 보내지지 않습니다. 5 월 그것은 어리석은 질문일지도 모르지만, 웹 사이트에서 테스트를 위해 내 로컬 컴퓨터에서 실행중인 이메일을 www가 호스트되기 전에 보낼 수있는 방법이 있습니다.이메일에 이미지 첨부하기

public static void SendMail(string emailBody, string to, string from, string subject) 
{ 
    MailMessage mailMessage = new MailMessage("[email protected]", "[email protected]"); 
    mailMessage.Subject = subject; 
    mailMessage.Body = emailBody; 
    mailMessage.IsBodyHtml = true; 
    //mailMessage.Body += "<br /><br /> <asp:Image ID='Image1' runat='server' ImageUrl='~/images/banner.jpg' />"; 

    string path = System.Web.HttpContext.Current.Server.MapPath(@"~/images/banner.jpg"); 
    AlternateView av1 = AlternateView.CreateAlternateViewFromString("<html><body><br/><img src=cid:companylogo/><br></body></html>" + emailBody, null, MediaTypeNames.Text.Html);LinkedResource logo = new LinkedResource(path); 
    av1.LinkedResources.Add(logo); 
    mailMessage.AlternateViews.Add(av1); 

    string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString; 
    using (SqlConnection con = new SqlConnection(cs)) 
    { 
     SqlCommand sc = new SqlCommand("SELECT EmailAdd FROM Volunteers where Country like 'United K%' and Race like 'Pak%' ", con); 
     con.Open(); 
     SqlDataReader reader = sc.ExecuteReader(); 
     if (reader.HasRows) 
     { 
      while (reader.Read()) 
      { 
       mailMessage.To.Add(reader[0].ToString()); 
      } 
     } 
     reader.Close(); 
    } 

    SmtpClient smtpClient = new SmtpClient(); 
    smtpClient.Send(mailMessage); 
} 
+1

''시험용으로 로컬 컴퓨터에서 실행중인 웹 사이트에서 전자 메일을 보낼 수있는 방법이 있습니다. "- 예, 물론입니다. 테스트를 위해 로컬 SMTP 수신기를 실행하십시오 : http://smtp4dev.codeplex.com – David

+1

'cs'와'sc'와 같은 변수를 어떻게 구별합니까? 나는 그 (것)들을 더 의미심장하게 지명 할 것입니다. – abatishchev

답변

0

이미지의 올바른 CID를 설정하지 않은 것처럼 보입니다. - 그것은 약간 중복 보인다

// Construct the MailMessage object to be relayed to the SMTP server 
message = new MailMessage("[email protected]", "[email protected]"); 

string path = System.Web.HttpContext.Current.Server.MapPath(@"~/images/banner.jpg"); 
byte[] image = LoadImageAsByteArray(path); 

// create a stream object from the file contents 
var stream = new MemoryStream(image); 

// create a mailAttachment object 
var mailAttachment = new System.Net.Mail.Attachment(stream, "bannerAttachment.jpg") 
        { 
         // set the content id of the attachment so our email src links are valid 
         ContentId = Guid.NewGuid().ToString("N") 
        }; 

// set the attachment inline so it does not appear in the mail client as an attachment 
mailAttachment.ContentDisposition.Inline = true; 

// and then add the newly created mailAttachment object to the Attachments collection 
message.Attachments.Add(mailAttachment); 

그리고 ... 나는 "이상한"발견 한 가지 AlternateView의 사용이 : 이것은 내 응용 프로그램 중 하나에서 사용하고 방법입니다. 나는 몸을 이렇게 창조 할 것을 조언 할 것이다 :

// Construct the body 
var body = string.Format("<html><body><br/><img src=cid:{0} /><br />{1}</body></html>", mailAttachment.ContentId, emailBody); 

// Subject 
message.Subject = "Whatever" 

// Ensure this is set to true so images are embedded correctly 
message.IsBodyHtml = true; 

// finally, add the body 
message.Body = body; 

// Create an smtp client object to initiate a connection with the server 
var client = new SmtpClient(smtpServerAddress, smtpServerPort.Value); 

// tell the client that we will be sending via the network (as opposed to using a pickup directory) 
client.DeliveryMethod = SmtpDeliveryMethod.Network; 

// and finally send the message 
client.Send(message); 

);

참고 : 내가 포함하지 않았기 때문에 자신의 인증 등을 처리해야합니다. 또한, 이것은 내 생산 코드의 발췌 내용이므로, 어떻게 진행되는지 알려주십시오. 그에 따라 내 대답을 수정하는 것보다 행복 할 것입니다.

+0

이 LoadImageAsByteArray 함수의 출처는 어디에도 없습니다. 공인되지 않았다고 선언 된 경우이 파일을 사용하려면 참조 할 DLL이 있어야합니다. –

+0

죄송합니다. 그 자체로 설명이 가능하다고 생각했습니다. http://stackoverflow.com/questions/1131116/pdf-to-byte-array-and-vice-versa 을 OR, 당신이 방법은 여기에 설명 사용할 수 있습니다 : 나는 방법이 여기에 설명 된 사용했습니다 http://stackoverflow.com/questions/7350679/convert-a-bitmap-into-a-byte-array-in-c – agAus

+0

이것이 당신에게 도움이 되었는가 동료가 아닌지 알면 좋을까요? – agAus

0

여기가 해결책입니다.

string ss = "<div style='background:#e0e1e3;width:800px; margin:20px auto;border:1px solid #d8d9db;'>"; 
       ss = ss + "<div style='background:#ffffff; padding:10px;'>"; 
       ss = ss + "<img src='http://example.com/images/myimage.jpg' /></div>"; 



    MailMessage MailMsg = new MailMessage(); 
       MailMsg.To.Add("[email protected]"); 
       MailMsg.From = new MailAddress("Test.co.in"); 
       MailMsg.Subject = "Your subject"; 
       MailMsg.BodyEncoding = System.Text.Encoding.UTF8; 
       MailMsg.IsBodyHtml = true; 
       MailMsg.Priority = MailPriority.High; 
       MailMsg.Body = ss; 
    SmtpClient tempsmtp = new SmtpClient(); 
       tempsmtp.Host = "smtp.gmail.com"; 
       tempsmtp.Port = 587; 
       tempsmtp.EnableSsl = true; 
       tempsmtp.Credentials = new System.Net.NetworkCredential("[email protected]", "welcome"); 
tempsmtp.DeliveryMethod = SmtpDeliveryMethod.Network; 
      tempsmtp.Send(MailMsg); 
+0

사용중인 이미지가 웹에 저장되어있는 것으로 보이고 이미지가 로컬 솔루션 폴더에 있습니다. 이메일. 웹 서버에 솔루션을 배포하기 전에 해당 기능을 테스트하고 있습니다. –

관련 문제