Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

238
Views
Adición de varios archivos adjuntos al correo electrónico desde el disco por iteración

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:

  1. los archivos PDF se guardan correctamente en el disco.
  2. durante la depuración, la lista de rutas de archivos es correcta.
  3. mientras que la depuración, los nombres de archivo y las rutas de archivo son distintos.

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:

  1. Usando newEmail.AttachFromFilename .
  2. Usando newEmail.Send en lugar de .SendAsync .
  3. Iterando sobre una matriz en lugar de una lista.
  4. Cambié mi host SMTP.
  5. Intenté usar ContentType para archivos PDF más antiguos (aunque tengo un software actualizado): "application/x-pdf" .

Pero nada de lo anterior hizo ninguna diferencia.

ingrese la descripción de la imagen aquí

Los tres elementos presentes son distintos, pero solo el último elemento se agrega como archivo en los 3 archivos adjuntos. ¿Importa ContentId ?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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

ingrese la descripción de la imagen aquí

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!