如何发送附件xamarin表单的电子邮件

时间:2018-04-26 07:35:15

标签: email xamarin xamarin.forms smtp system.net.mail

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" />

我想发送一封附件的电子邮件。如果我删除附件的代码,则电子邮件将发送给收件人。当我使用附件的代码时,不会发送电子邮件。我不知道为什么......

2 个答案:

答案 0 :(得分:0)

它失败了,因为你没有在附件变量中添加文件:

System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment();
mail.Attachments.Add(attachment);

答案 1 :(得分:0)

您需要向新的System.Net.Mail.Attachment构造函数的参数添加文件路径

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

但是,还有其他选择。参见this Microsoft documentation。 您可以输入流而不是字符串(文件路径)。

我认为以下内容可能对您有用:

attachment = new System.Net.Mail.Attachment(fileLabel.Text);