c#MailMessage:使用默认电子邮件帐户

时间:2015-08-05 10:47:24

标签: c# email mailmessage

我使用MailMessage功能从我的winforms应用程序发送电子邮件。

我编译电子邮件,将其保存到磁盘,然后默认邮件客户端将打开邮件,以便用户在点击发送之前验证设置。

我想设置' From'电子邮件自动发送到邮件客户端中设置的默认电子邮件帐户。我怎么能这样做?

var mailMessage = new MailMessage();
mailMessage.From = new MailAddress(fromEmailAccount);
mailMessage.To.Add(new MailAddress("recipient@work.com"));
mailMessage.Subject = "Mail Subject";
mailMessage.Body = "Mail Body";

如果我将fromEmailAccount留空,我会收到错误,如果我将其设置为' test@test.com'由于本地帐户无权通过未知帐户发送电子邮件,因此电子邮件不会发送。

2 个答案:

答案 0 :(得分:1)

从操作系统中获取用户信息(如果是Windows 8,10),他们将用户设置为用户电子邮件,请参阅此问题:Get user information in Windows 8?

答案 1 :(得分:0)

我已经测试了以下代码,这似乎从地址获取本地默认邮件并启动邮件消息窗口,希望它有所帮助:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Outlook = Microsoft.Office.Interop.Outlook;

namespace testMailEmailUser
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Outlook.Application application = new Outlook.Application();
            Outlook.AddressEntry mailSender = null;

            Outlook.Accounts accounts = application.Session.Accounts;

            foreach (Outlook.Account account in accounts)
            {
                mailSender = account.CurrentUser.AddressEntry;
            }

            Outlook.MailItem mail =
                application.CreateItem(
                Outlook.OlItemType.olMailItem)
                as Outlook.MailItem;

            if (mailSender != null)
            {
                mail.To = "someone@example.com; another@example.com";
                mail.Subject = "Some Subject Matter";
                mail.Body = "Some Body Text";
                mail.Sender = mailSender;
                mail.Display(false);
            }
        }

    }
}