0 votes

At this time we need you to point us to asp.net core samples of sending emails with attachments.

The code we see on your site does not explain the use of file stream or upload input. We need to dynamically identify the path of the uploaded file if we are to use your code and that is a difficult thing to do.

This is your code.

// Read attachment from disk, add it to Attachments collection
MimeData attachment = builder.AddAttachment(@"../image.jpg");

Thanks
Luis

by

1 Answer

0 votes

You can create attachment from a byte array:

byte[] attData = new byte[3] { 1, 2, 3 };
MimeData attachment = builder.AddAttachment(attData);

For example:

[HttpPost("upload")]
public async Task<IActionResult> UploadFile()
{
    using (var memory = new MemoryStream())
    {
        await Request.Body.CopyToAsync(memoryStream);  

        MailBuilder builder = new MailBuilder();

        MimeData attachment = builder.AddAttachment(
            memory.ToArray());

        attachment.FileName = "image.jpg";
        attachment.ContentId = "logo@example.com";

        builder.From.Add(new MailBox("from@example.com"));
        builder.To.Add(new MailBox("to@example.com"));
        builder.Subject = "Subject";

        IMail email = builder.Create();

        // send message
        using(Smtp smtp = new Smtp())
        {
            smtp.Connect("smtp.server.com");
            smtp.UseBestLogin("user", "password");

            smtp.SendMessage(email);                     
            smtp.Close();   
        }        
    }
    return Ok("File received successfully");
}

In most cases you'd probably need to store several uploaded attachments in some temporary session cache or even a database.

by (302k points)
...