Sending an attachment that the user chose with mail

后端 未结 2 1149
野性不改
野性不改 2021-01-16 01:05

The problem:

I want that users can send me mails with attachments. They can choose the file with an input file button in html. The problem is that i

2条回答
  •  悲&欢浪女
    2021-01-16 01:44

    Below a complete example to add files to an email message as attachment without writing them to the disk.

    using (SmtpClient client = new SmtpClient())
    using (MailMessage message = new MailMessage())
    {
        client.Host = "host.com";
        client.Port = 25;
        client.Timeout = 10000;
        client.EnableSsl = false;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.UseDefaultCredentials = false;
        client.Credentials = new NetworkCredential("user", "pass");
    
        message.From = new MailAddress("email@from.nl", "VDWWD");
        message.To.Add(new MailAddress("email@to.nl"));
        message.Subject = "Your uploaded files";
        message.IsBodyHtml = true;
        message.Body = "The files you uploaded.";
    
        //loop all the uploaded files
        foreach (var file in FileUpload1.PostedFiles)
        {
            //add the file from the fileupload as an attachment
            message.Attachments.Add(new Attachment(file.InputStream, file.FileName, MediaTypeNames.Application.Octet));
        }
    
        //send mail
        try
        {
            client.Send(message);
        }
        catch (Exception ex)
        {
            //handle error
        }
    }
    

提交回复
热议问题