c# MailMessage:使用默认的电子邮件帐户发送邮件
本文关键字:电子邮件 MailMessage 默认 | 更新日期: 2023-09-27 18:06:32
我通过使用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'的东西,电子邮件不发送,因为本地帐户没有权限通过未知帐户发送它。
从操作系统获取用户信息(如果windows 8、10)他们将from设置为用户邮箱,参见本题:在windows 8中获取用户信息?
我已经测试了下面的代码,这似乎从地址抓取本地默认邮件并启动邮件消息窗口,希望它有帮助:
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);
}
}
}
}