我使用以下代码发送邮件。但我只能添加一个附件。我想用一封邮件添加超过30个附件。我怎么解决这个问题。请帮帮我。
string fromEmail = "abcd@gmail.com ";
mail_add=recever@gmail.com
MailMessage mailMessage = new MailMessage(fromEmail, mail_add, subject, subject);
System.Net.Mail.Attachment attachement;
attachement = new System.Net.Mail.Attachment("path_with_xl_file");
mailMessage.Attachments.Add(attachement);
mailMessage.Body = body;
MailAddress copy = new MailAddress(fromEmail );
mailMessage.CC.Add(copy);
SmtpClient smtpClient = new SmtpClient();
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587
smtpClient.EnableSsl = false;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential(fromEmail, "mis123");
try
{
smtpClient.Send(mailMessage);
}
答案 0 :(得分:1)
您可以多次执行mailMessage.Attachments.Add
:
mailMessage.Attachments.Add(new System.Net.Mail.Attachment("path_with_xl_file"));
mailMessage.Attachments.Add(new System.Net.Mail.Attachment("path_with_xl_file_2"));
mailMessage.Attachments.Add(new System.Net.Mail.Attachment("path_with_xl_file_3"));
mailMessage.Attachments.Add(new System.Net.Mail.Attachment("path_with_xl_file_4"));
当然,您可以通过使用数组,循环和其他语言工具来简化此代码。这取决于您如何在程序中存储这30个文件
例如,如果将所有路径存储在string
数组中,则可以执行以下操作:
string[] pathes = /* ... */;
foreach (var path in pathes)
{
mailMessage.Attachments.Add(new System.Net.Mail.Attachment(path));
}
答案 1 :(得分:0)
以下是执行此操作的示例代码。此代码假定您已经将一组文件路径转换为Attachments
。
private static void SendEmail(IEnumerable<string> attachmentFilePaths)
{
string fromEmail = "abcd@gmail.com ";
string mail_add = "recever@gmail.com";
string subject = "hello";
string body = "How are you?";
try
{
using (MailMessage mailMessage = new MailMessage(fromEmail, mail_add, subject, body))
{
foreach (var attachmentFilePath in attachmentFilePaths)
{
if (File.Exists(attachmentFilePath))
{
Attachment attachement = new Attachment(attachmentFilePath);
mailMessage.Attachments.Add(attachement);
}
}
MailAddress copy = new MailAddress(fromEmail);
mailMessage.CC.Add(copy);
using (SmtpClient smtpClient = new SmtpClient())
{
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.EnableSsl = false;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential(fromEmail, "mis123");
smtpClient.Send(mailMessage);
}
}
}catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}