ACTUALIZAR Probé esto con documentos de Excel en lugar de archivos PDF, y funcionó. ¿Por qué no funciona con archivos PDF?
Estoy tratando de agregar una cantidad X de archivos adjuntos a un correo electrónico iterando sobre una lista de cadenas de ruta de archivo. En cambio, recibo X archivos adjuntos, pero todos son copias del mismo archivo. Entonces, la cantidad de archivos adjuntos es correcta, pero su contenido no lo es.
Esto sucede a pesar de que:
Estoy usando FluentEmail para enviar correos electrónicos. Además, me baso en el siguiente ejemplo (consulte la sección 'Múltiples archivos adjuntos').
Debug.WriteLine(path) solo para verificar si puedo generar correctamente las cadenas en el ciclo, que era.
Mi método:
public async void SendInvoicesEmail() { try { using (SqlConnection con = new(ConnectionString.connectionString)) using (SqlCommand cmd = new("query text", con)) { con.Open(); SmtpSender sender = new SmtpSender(() => new SmtpClient(host: "smtp.office365.com") { EnableSsl = true, UseDefaultCredentials = false, DeliveryMethod = SmtpDeliveryMethod.Network, Credentials = new NetworkCredential("email", "password"), Port = 587 }); Email.DefaultSender = sender; IFluentEmail newEmail = Email .From("email") .To("email") .Subject("subject text") .Body("body text"); var attachList = new List<FluentEmail.Core.Models.Attachment>(); // SourcePathList contains all the file paths I need to reference. foreach (string path in SourcePathList) { string fileName = Path.GetFileName(path); var attachment = new FluentEmail.Core.Models.Attachment { Data = File.OpenRead(path), ContentType = "application/pdf", Filename = $"{fileName}" }; attachList.Add(attachment); Debug.WriteLine(path); } newEmail.Attach(attachList); SourcePathList.Clear(); FluentEmail.Core.Models.SendResponse result = await newEmail.SendAsync(); if (result.Successful) { cmd.ExecuteNonQuery(); } } } catch (Exception ex) { MessageBox.Show(ex.Message, "Message", MessageBoxButton.OK, MessageBoxImage.Information); } }Yo he tratado:
newEmail.AttachFromFilename .newEmail.Send en lugar de .SendAsync .ContentType para archivos PDF más antiguos (aunque tengo un software actualizado): "application/x-pdf" .Pero nada de lo anterior hizo ninguna diferencia.
Los tres elementos presentes son distintos, pero solo el último elemento se agrega como archivo en los 3 archivos adjuntos. ¿Importa ContentId ?
Creo que el objeto de transmisión no se actualiza en bucle y agrega el mismo contenido de archivo para cada archivo adjunto.
debe usar su objeto de flujo al usar la declaración como se muestra a continuación
También estoy usando una funcionalidad similar en mi web usando System.Net.Mail
Anteriormente sugerí un código no probado, que tenía un error. Ahora he probado su código nuevamente y funciona como se esperaba. aquí está el método completo que he ejecutado en un controlador MVC.
public async void SendInvoicesEmail() { try { SmtpSender sender = new SmtpSender(() => new SmtpClient(host: "smtp.sendgrid.net") { EnableSsl = true, UseDefaultCredentials = false, DeliveryMethod = SmtpDeliveryMethod.Network, Credentials = new NetworkCredential("user", "password"), Port = 587 }); Email.DefaultSender = sender; IFluentEmail newEmail = Email .From("Admin@admin.com") .To("user@user.com") .Subject("I am feeling lucky") .Body("This email is for stack overflow problem solution."); var attachList = new List<FluentEmail.Core.Models.Attachment>(); // SourcePathList contains all the file path on my machine. var SourcePathList = new List<string> { "C:\\Consolidate_09122021085902.xlsx", "C:\\PaySlip_15022022075604.xlsx", "C:\\RateCard_14022022104134.xlsx" }; foreach (string path in SourcePathList) { string fileName = Path.GetFileName(path); var attachment = new FluentEmail.Core.Models.Attachment { Data = System.IO.File.OpenRead(path), ContentType = "application/pdf", Filename = $"{fileName}" }; attachList.Add(attachment); Debug.WriteLine(path); } newEmail.Attach(attachList); SourcePathList.Clear(); FluentEmail.Core.Models.SendResponse result = await newEmail.SendAsync(); } catch (Exception ex) { // write log file } }Aquí está la salida de correo electrónico