2014-02-07 4 views
0

Я пытаюсь отправить тестовую электронную почту с моей локальной машины-разработчика, с изображением. изображение не отправляется как вложение. Может быть, это глупый вопрос, но есть ли способ отправить электронную почту с моего веб-сайта, запущенного на моей локальной машине, для тестирования, прежде чем я размещу его на 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

Похоже, что вы не можете установить правильный идентификатор изображения. Это метод я использую в одном из моих приложений:

// 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 ИЛИ, вы можете использовать метод, описанный здесь: 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

кажется, что изображение, которое вы используете, помещено в Интернет, мое изображение находится в моей локальной папке решения, я хочу прикрепить его к Эл. адрес. Я тестирую эту функциональность, прежде чем я развертываю решение для веб-сервера. –

Смежные вопросы