简体   繁体   English

发送带有C#和XAML附件的电子邮件

[英]Send an email with attachment with C# and XAML

I am building a windows 8 desktop app. 我正在构建Windows 8桌面应用程序。 I have an email form with a textbox and a button. 我有一个带有文本框和按钮的电子邮件表单。 XAML below. 下面的XAML。

<TextBox x:Name="email_txt"></TextBox>
<Button x:Name="email_btn" Content="Emial Me"  Click="email_btn_Click"/>

How do I send a an email with an attachment to the email address entered in email_txt when email_btn is clicked. 如何发送一封电子邮件,附件中输入的电子邮件地址email_txtemail_btn被点击。

I used the following in the c# code behind the XAML page 我在XAML页面后面的c#代码中使用了以下内容

 private async void email_btn_Click(Object sender, RoutedEventArgs e)
        {
            var mailto = new Uri("mailto:?to=tr@gmail.com&subject=Hello&body=Test Tocuh Email");
            await Windows.System.Launcher.LaunchUriAsync(mailto);*/

        }

This code just opens MS Outlook with the message type. 此代码仅使用消息类型打开MS Outlook。

How do I send an email with an attachment when the button is clicked? 单击按钮后如何发送带有附件的电子邮件?

Consider using SmtpClient class. 考虑使用SmtpClient类。 Note that this class by default will take smtp configurations from you application config file. 请注意,此类默认情况下将从应用程序配置文件中获取smtp配置。

        var mailMessage = new MailMessage("test@example.com", email_txt.Text, "Hello", "Test");
        mailMessage.IsBodyHtml = true;
        byte[] attachmentData; //get attachment data as byte array.
        var attachmentStream = new MemoryStream(attachmentData);
        var attachment = new Attachment(attachmentStream, "Test");

        mailMessage.Attachments.Add(attachment);

        var smtpClient = new SmtpClient(smtpServer);
        smtpClient.Send(mailMessage);

The WinRT (Win App) platform doesn't have any built-in SMTP client. WinRT(Win App)平台没有任何内置的SMTP客户端。 Instead you can use the share charm in order to send emails. 相反,您可以使用共享超级按钮发送电子邮件。

See Sharing content source app sample . 请参阅共享内容源应用程序示例

I would include some code, but I'm not on my Windows 8 machine. 我会包含一些代码,但是我不在Windows 8计算机上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM