我目前正在使用Windows服务,该服务使用Exchange Web Service API从邮箱收集电子邮件,并将电子邮件中的数据传递到存储过程。然后,存储过程将此数据添加到SSMS中的表中。我已经手动测试了存储过程,并且功能正常。我还提供了一种写入文本文件的方法,并且可以收集电子邮件的所有方面(收件人,日期,主题等)。
我的问题是只有邮箱中的最新电子邮件才被传递到数据库。下面是我的代码:
int offset = 0;
int pageSize = 50;
bool moreEmails = true;
ItemView view = new ItemView(pageSize, offset, OffsetBasePoint.Beginning);
view.PropertySet = PropertySet.IdOnly;
FindItemsResults<Item> findResults;
List<EmailMessage> emails = new List<EmailMessage>();
findResults = service.FindItems(WellKnownFolderName.Inbox, view);
while (moreEmails)
{
foreach (var item in findResults.Items)
{
emails.Add((EmailMessage)item);
}
moreEmails = findResults.MoreAvailable;
if (moreEmails)
{
view.Offset += pageSize;
}
}
PropertySet properties = (BasePropertySet.FirstClassProperties);
service.LoadPropertiesForItems(emails, properties);
foreach (var EmailParam in emails)
{
FromEmail = EmailParam.From.ToString();
EmailDate = EmailParam.DateTimeReceived.ToString("yyyy-MM-dd hh:mm:ss");
EmailSubject = EmailParam.Subject;
EmailBody = EmailParam.Body;
int SourceID = 1;
foreach (var recipient in EmailParam.ToRecipients)
{
ToEmail += recipient.Address.ToString();
}
foreach (var cc in EmailParam.CcRecipients)
{
Emailcc += cc.Address.ToString();
}
using (SqlConnection con = new SqlConnection(conStr))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("mtsp_CreateTicket", con);
da.SelectCommand.CommandType = System.Data.CommandType.StoredProcedure;
da.SelectCommand.Parameters.AddWithValue("@Date", EmailDate);
da.SelectCommand.Parameters.AddWithValue("@FromEmail", FromEmail);
da.SelectCommand.Parameters.AddWithValue("@ToEmail", ToEmail);
da.SelectCommand.Parameters.AddWithValue("@EmailSubject", EmailSubject);
da.SelectCommand.Parameters.AddWithValue("@EmailBody", EmailBody);
da.SelectCommand.Parameters.AddWithValue("@Emailcc", Emailcc);
da.SelectCommand.Parameters.AddWithValue("@SourceID", SourceID);
da.SelectCommand.ExecuteNonQuery();
}
}
这是我第一次使用Windows服务,对此我有点陌生,因此非常感谢您的帮助。谢谢!