Mail Attachments using smtpclient

Hello, I'm new to all this xamarin-things. I'm stuck on one pretty simple things. I can't send mail messages with photos attached to them.

I'm writing Xamarin.Forms ios application.
This is how I code it:

method to send a message:
public string SendMessageMail(string theme, string message, List files, string mainAdress)
{
var result = "error";
try
{
MailMessage mail = new MailMessage();

    mail.From = new MailAddress(@"[email protected]");
    mail.To.Add(mainAdress == string.Empty ? Catalog.personalManager.email : mainAdress);
    mail.Subject = "Subject";

    string text = string.Empty;

    text = @"<html><head><title></title></head><body><table border='1' width='100%' cellpadding='10'>";

    text += String.Format(@"<p>Добрый день!</p><br>", Catalog.User.title);
    text += @"<p>Subject: " + theme + "</p><br>";
    text += @"<p>Message: " + message + "</p><br>";

    if (files != null && files.Count > 0)
    {
        foreach (var file in files)
            mail.Attachments.Add(new Attachment(file));
    }

    text += @"</body></html>";

    mail.Body = text;
    mail.IsBodyHtml = true;

    SmtpClient smtpServer = new SmtpClient(@"smtp.yandex.ru", 587);
    smtpServer.UseDefaultCredentials = false;
    smtpServer.EnableSsl = true;
    smtpServer.Credentials = new NetworkCredential(@"user", @"pass");

    smtpServer.SendAsync(mail, null);

    result = "Done";
}
catch (Exception ex)
{
    result = "Error";
}
return result;

}

I call it using this method:
public void SendMail(IEnumerable mailAddresses, string message, string subject)
{
var mails = mailAddresses.Select(m => m);
//var items = pFiles.Items.ToList();
var items = _images
.Select(i => i.path)
.ToList();

System.Threading.Tasks.Task.Run(() =>
{
    foreach (var mail in mails)
    {
        var res = Catalog.Methods.SendMessageMail(
            subject,
            message,
            items,
            mail);
    }
});

}

Sometimes I can send 1 or 2 files attached message, but sometimes code fails on this line telling there is no file with such path:
if (files != null && files.Count > 0)
{
foreach (var file in files)
mail.Attachments.Add(new Attachment(file));
}

To select a picture I call this method:
private async Task SelectPicture()
{
try
{
var mediaFile = await this._mediaPicker.SelectPhotoAsync(new CameraMediaStorageOptions
{
DefaultCamera = CameraDevice.Front,
MaxPixelDimension = 400
});
return mediaFile.Path;

}
catch (System.Exception ex)
{
    return string.Empty;
}

}

Help me please.
Thanks in advance

Answers

Sign In or Register to comment.