1

C#:

private  void SendEmail(object sender, EventArgs e)
        {
            string subject = "subject here ";
            string body = "body here ";
                var mail = new MailMessage();
                var smtpServer = new SmtpClient("smtp.gmail.com", 587);
                mail.From = new MailAddress("veezo2007pk@gmail.com");
                mail.To.Add("veezo2009pk@gmail.com");
                mail.Subject = subject;
                mail.Body = body;
                System.Net.Mail.Attachment attachment;
                attachment = new System.Net.Mail.Attachment();
                mail.Attachments.Add(attachment);
                smtpServer.Credentials = new NetworkCredential("veezo2007pk", "password");

                smtpServer.UseDefaultCredentials = false;
                smtpServer.EnableSsl = true;
                smtpServer.Send(mail);

        }

private async void File(object sender, EventArgs e)
        {


          var file = await CrossFilePicker.Current.PickFile();                      

            if (file != null)
            {
                fileLabel.Text = filepath;
            }
        }

XAML:

 <Entry Placeholder="Phone No" x:Name="Phone" />  
                <Button Text="Pick a file" x:Name="fileButton" Clicked="File"/>
                    <Label Text="This is FileName" x:Name="fileLabel"/>    
                <Button Text="Submit" Clicked="SendEmail" BackgroundColor="Crimson" TextColor="White" WidthRequest="100" />

I want to send an email with an attachment. If I remove the code for the attachment the email gets to the recipient. When I am using the code for the attachment the email is not sent. I don't know why....

Sjoerd Pottuit
  • 2,307
  • 4
  • 20
  • 35
waqas waqas
  • 197
  • 9
  • 22
  • Possible duplicate of [Adding an attachment to email using C#](https://stackoverflow.com/questions/5034503/adding-an-attachment-to-email-using-c-sharp) – Sjoerd Pottuit Nov 08 '18 at 14:03

2 Answers2

0

It fails because at no point do you add a file to the attachment variable:

System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment();
mail.Attachments.Add(attachment);
Sjoerd Pottuit
  • 2,307
  • 4
  • 20
  • 35
Adam
  • 1,249
  • 1
  • 10
  • 11
0

You need to add a file path to the parameters of the new System.Net.Mail.Attachment constructor:

attachment = new System.Net.Mail.Attachment("enter file path here");

However, there are other options as well. See this Microsoft documentation. You can enter a Stream instead of a string (the file path).

I think the following might work for you:

attachment = new System.Net.Mail.Attachment(fileLabel.Text);
Sjoerd Pottuit
  • 2,307
  • 4
  • 20
  • 35