首页 > 解决方案 > 如何发送带有附件 xamarin 表单的电子邮件

问题描述

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

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

标签: emailxamarinxamarin.formssmtpsystem.net.mail

解决方案


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

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

但是,还有其他选择。请参阅此 Microsoft 文档。您可以输入 Stream 而不是字符串(文件路径)。

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

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

推荐阅读