Usuário com melhor resposta
Enviar email com imagem gravada no banco

Pergunta
-
Boa tarde!
Eu precisava enviar um e-mail com imagens gravada no banco.
Exemplo: eu tenho um console application que dispara uns email que estão gravados no banco. No banco de dados eu tenho o nome da imagem gravada já estou conseguindo enviar todos os campos mas a imagem não chega no e-mail enviado alguem teria alguma solução. Esta imagens está em outra aplicação é um projeto web mvc3. estou tentando desta forma mas não tive sucesso.
Aguardo.
public static void Enviar() { BasicBL<EmailMkt> _emailMkt = new BasicBL<EmailMkt>(); BasicBL<EmailMktUsuarios> _emailMktUsuarios = new BasicBL<EmailMktUsuarios>(); EmailMkt emailMkt = new EmailMkt(); var retornoLista = new List<DisparaEmailViewModel>(); var lista = _emailMkt.GetAll().Where(x=> x.DataEnvio == null).ToList(); foreach (var email in lista) { var model = new DisparaEmailViewModel(); model.Id = email.Id; model.Assunto = email.Assunto; model.EmailRemetente = email.EmailRemetente; model.CorpoEmail = email.CorpoEmail; model.Foto = email.Foto; model.Usuario = (from x in _emailMktUsuarios.GetAll() where x.IdEmailMkt == email.Id select x.Usuario).ToList(); foreach (var usuario in model.Usuario) { string corpo = "<html><body><img src='http://200.218.13.42/vendogafisa/locales/global/upload/img/'>" + model.Foto + "</body></html>"; SmtpClient client = new SmtpClient(); MailAddress de = new MailAddress(model.EmailRemetente); MailAddress para = new MailAddress(usuario.Email); MailAddressCollection Emails = new MailAddressCollection(); MailMessage mensagens = new MailMessage(de, para); mensagens.IsBodyHtml = true; mensagens.Subject = model.Assunto; mensagens.Body = model.CorpoEmail + corpo; client.Send(mensagens); client.Dispose(); } retornoLista.Add(model); emailMkt = _emailMkt.Find(x => x.Id == model.Id).First(); emailMkt.DataEnvio = DateTime.Now; _emailMkt.SaveChanges(); } }
Respostas
-
Duas dúvidas Vitor, Eu posso usar o meu metodo de cima e só utilizar está parte do código?
email.Body = "<div style=\"font-family:Arial\">This is an INLINE attachment:<br /><br /><img src=\"@@IMAGE@@\" alt=\"\"><br /><br />Thanks for downloading this example.</div>"; // generate the contentID string using the datetime string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "@zofm"; // create the INLINE attachment string attachmentPath = Environment.CurrentDirectory + @"\test.png"; Attachment inline = new Attachment(attachmentPath); inline.ContentDisposition.Inline = true; inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline; inline.ContentId = contentID; inline.ContentType.MediaType = "image/png"; inline.ContentType.Name = Path.GetFileName(attachmentPath); email.Attachments.Add(inline); // replace the tag with the correct content ID email.Body = email.Body.Replace("@@IMAGE@@", "cid:" + contentID);
A outra dúvida seria, eu tenho um projeto web e dentro do projeto web eu tenho um console application que vai fazer todo o envio que eu vou programar no windows. Como eu passo o endereço aqui da image. tipo a imagem está salva dentro de locales/global/img que está no projeto web.
Obrigado!!
<img src=\"@@IMAGE@@\" alt=\"\">
1° Duvida:
Pode usar apenas o trecho de código, seria até mais fácil adaptar a sua rotina, apenas inverta o código pois o que eu passei te um erro, use assim:
email.Body = "<div style=\"font-family:Arial\">This is an INLINE attachment:<br /><br /><img src=\"@@IMAGE@@\" alt=\"\"><br /><br />Thanks for downloading this example.</div>"; // create the INLINE attachment string attachmentPath = Environment.CurrentDirectory + @"\test.png"; // generate the contentID string using the datetime string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "@zofm"; Attachment inline = new Attachment(attachmentPath); inline.ContentDisposition.Inline = true; inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline; inline.ContentId = contentID; inline.ContentType.MediaType = "image/png"; inline.ContentType.Name = Path.GetFileName(attachmentPath); email.Attachments.Add(inline); // replace the tag with the correct content ID email.Body = email.Body.Replace("@@IMAGE@@", "cid:" + contentID);
2° Duvida
Certamente sua aplicação console tem um app.config, adicione dentro do appsettings uma chave que possua o caminho até a sua pasta com as imagens e mude esta linha para recuperar o arquivo:
Exemplo de key:
<appSettings> <add value="C:\caminhoDaAplicacao\fotos\" key="CaminhoFotos" /> </appSettings>
E use algo deste tipo para recuperar o arquivo:
string attachmentPath = ConfigurationManager.AppSettings["CaminhoFotos"] + model.foto;
Vitor Mendes | Seu feedback é muito importante para todos!
Visite o meu site: http://www.vitormendes.com.br/- Marcado como Resposta cleiton costa segunda-feira, 11 de junho de 2012 19:52
- Editado Vitor Mendes segunda-feira, 11 de junho de 2012 19:56
Todas as Respostas
-
Este propriedade .Foto é de que tipo ? É o caminho da imagem, um array de bytes ?
model.Foto
Vitor Mendes | Seu feedback é muito importante para todos!
Visite o meu site: http://www.vitormendes.com.br/ -
-
Isso eu pego o nome da foto(arquivo) que está gravado no banco. que é dinamico.
exemplo: carro.jpg
O arquivo esta gravado no banco de dados em uma coluna do tipo varbinary(MAX) ou apenas o nome da foto, cujo as fotos esta em alguma pasta no servidor ??Vitor Mendes | Seu feedback é muito importante para todos!
Visite o meu site: http://www.vitormendes.com.br/ -
-
eu gravo em um campo string o nome da foto, quando eu quero visualizar a foto eu concateno o caminho + o nome do arquivo. as fotos ficam gravadas em um diretório dentro de projeto. locales/global/img/
Ótimo Cleiton era isso que eu queria saber, na internet tem diversos tutorias de como attachar uma imagem no corpo do e-mail, vou deixar aqui um código para registro e alguns links que pode te ajudar, só passar o path da imagem, apenas cuidado quanto ao MediaType da sua imagem (png, jpg, gif e etc...):
using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Net.Mail; using System.Net.Mime; namespace devSmtp { class Program { static void Main(string[] args) { // This example show you how to send one email message with an INLINE attachment. // You can use this example also without the support of CDO or other type of SmtpClient. // creating the email message MailMessage email = new MailMessage("test@yourdomain.something", "test@yourdomain.something"); // information email.Subject = "INLINE attachment TEST"; email.IsBodyHtml = true; email.Body = "<div style=\"font-family:Arial\">This is an INLINE attachment:<br /><br /><img src=\"@@IMAGE@@\" alt=\"\"><br /><br />Thanks for downloading this example.</div>"; // generate the contentID string using the datetime string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "@zofm"; // create the INLINE attachment string attachmentPath = Environment.CurrentDirectory + @"\test.png"; Attachment inline = new Attachment(attachmentPath); inline.ContentDisposition.Inline = true; inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline; inline.ContentId = contentID; inline.ContentType.MediaType = "image/png"; inline.ContentType.Name = Path.GetFileName(attachmentPath); email.Attachments.Add(inline); // replace the tag with the correct content ID email.Body = email.Body.Replace("@@IMAGE@@", "cid:" + contentID); // sending the email with the SmtpDirect class (not using the System.Net.Mail.SmtpClient class) SmtpDirect smtp = new SmtpDirect("localhost"); smtp.Send(email); email.Dispose(); } } }
http://www.codeproject.com/Articles/34467/Sending-Email-Using-Embedded-Images
http://www.example-code.com/csharp/HtmlEmbeddedImage.asp
http://www.systemnetmail.com/faq/4.4.aspx
Vitor Mendes | Seu feedback é muito importante para todos!
Visite o meu site: http://www.vitormendes.com.br/ -
Duas dúvidas Vitor, Eu posso usar o meu metodo de cima e só utilizar está parte do código?
email.Body = "<div style=\"font-family:Arial\">This is an INLINE attachment:<br /><br /><img src=\"@@IMAGE@@\" alt=\"\"><br /><br />Thanks for downloading this example.</div>"; // generate the contentID string using the datetime string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "@zofm"; // create the INLINE attachment string attachmentPath = Environment.CurrentDirectory + @"\test.png"; Attachment inline = new Attachment(attachmentPath); inline.ContentDisposition.Inline = true; inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline; inline.ContentId = contentID; inline.ContentType.MediaType = "image/png"; inline.ContentType.Name = Path.GetFileName(attachmentPath); email.Attachments.Add(inline); // replace the tag with the correct content ID email.Body = email.Body.Replace("@@IMAGE@@", "cid:" + contentID);
A outra dúvida seria, eu tenho um projeto web e dentro do projeto web eu tenho um console application que vai fazer todo o envio que eu vou programar no windows. Como eu passo o endereço aqui da image. tipo a imagem está salva dentro de locales/global/img que está no projeto web.
Obrigado!!
<img src=\"@@IMAGE@@\" alt=\"\">
-
Duas dúvidas Vitor, Eu posso usar o meu metodo de cima e só utilizar está parte do código?
email.Body = "<div style=\"font-family:Arial\">This is an INLINE attachment:<br /><br /><img src=\"@@IMAGE@@\" alt=\"\"><br /><br />Thanks for downloading this example.</div>"; // generate the contentID string using the datetime string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "@zofm"; // create the INLINE attachment string attachmentPath = Environment.CurrentDirectory + @"\test.png"; Attachment inline = new Attachment(attachmentPath); inline.ContentDisposition.Inline = true; inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline; inline.ContentId = contentID; inline.ContentType.MediaType = "image/png"; inline.ContentType.Name = Path.GetFileName(attachmentPath); email.Attachments.Add(inline); // replace the tag with the correct content ID email.Body = email.Body.Replace("@@IMAGE@@", "cid:" + contentID);
A outra dúvida seria, eu tenho um projeto web e dentro do projeto web eu tenho um console application que vai fazer todo o envio que eu vou programar no windows. Como eu passo o endereço aqui da image. tipo a imagem está salva dentro de locales/global/img que está no projeto web.
Obrigado!!
<img src=\"@@IMAGE@@\" alt=\"\">
1° Duvida:
Pode usar apenas o trecho de código, seria até mais fácil adaptar a sua rotina, apenas inverta o código pois o que eu passei te um erro, use assim:
email.Body = "<div style=\"font-family:Arial\">This is an INLINE attachment:<br /><br /><img src=\"@@IMAGE@@\" alt=\"\"><br /><br />Thanks for downloading this example.</div>"; // create the INLINE attachment string attachmentPath = Environment.CurrentDirectory + @"\test.png"; // generate the contentID string using the datetime string contentID = Path.GetFileName(attachmentPath).Replace(".", "") + "@zofm"; Attachment inline = new Attachment(attachmentPath); inline.ContentDisposition.Inline = true; inline.ContentDisposition.DispositionType = DispositionTypeNames.Inline; inline.ContentId = contentID; inline.ContentType.MediaType = "image/png"; inline.ContentType.Name = Path.GetFileName(attachmentPath); email.Attachments.Add(inline); // replace the tag with the correct content ID email.Body = email.Body.Replace("@@IMAGE@@", "cid:" + contentID);
2° Duvida
Certamente sua aplicação console tem um app.config, adicione dentro do appsettings uma chave que possua o caminho até a sua pasta com as imagens e mude esta linha para recuperar o arquivo:
Exemplo de key:
<appSettings> <add value="C:\caminhoDaAplicacao\fotos\" key="CaminhoFotos" /> </appSettings>
E use algo deste tipo para recuperar o arquivo:
string attachmentPath = ConfigurationManager.AppSettings["CaminhoFotos"] + model.foto;
Vitor Mendes | Seu feedback é muito importante para todos!
Visite o meu site: http://www.vitormendes.com.br/- Marcado como Resposta cleiton costa segunda-feira, 11 de junho de 2012 19:52
- Editado Vitor Mendes segunda-feira, 11 de junho de 2012 19:56
-