添加电子邮件addressCollection to,cc,bcc和replytoList

时间:2011-07-22 06:59:47

标签: email system.net.mail email-address

我想将MailAddressCollection添加到我的MailMessage(Net.Mail)的to,cc,bcc和replytolist

我的代码赞

   MessageEntity.To.Add(GetMailAddress(TOEmailAddress));
   MessageEntity.CC.Add(GetMailAddress(CCEmailAddress));
   MessageEntity.Bcc.Add(GetMailAddress(BCCEmailAddress));
   MessageEntity.RepltToList.Add(GetMailAddress(ReplyEmailAddress));


    private static MailAddressCollection GetMailAddress(List<string> LstMailAddress)
    {
        MailAddressCollection MAddressCollection = new MailAddressCollection();
        if (MailAddress != null)
        {
            foreach (string EmailAddress in MailAddress)
            {
                if (IsValidEmailId(EmailAddress))
                {
                    MAddressCollection.Add((new MailAddress(EmailAddress)));
                }
            }
        }
        return MAddressCollection;
    }

显示错误无法从'System.Net.Mail.MailAddressCollection'转换为'string'

是否可以将EmailAddressCollection添加到电子邮件到/ cc / bcc / ReplyToList?

由于 圣

1 个答案:

答案 0 :(得分:0)

使用快速重构器,您可以这样做:

AddMailAddresses(MessageEntity.To, TOEmailAddress);
AddMailAddresses(MessageEntity.CC, CCEmailAddress);
AddMailAddresses(MessageEntity.Bcc, BCCEmailAddress);
AddMailAddresses(MessageEntity.ReplyToList, ReplyEmailAddress);

private static void AddMailAddresses(
    MailAddressCollection mailAddresses,
    IEnumerable<string> mailAddressesToAdd)
{
    if (mailAddressesToAdd == null)
    {
        return;
    }

    IEnumerable<string> validMailAddressesToAdd = 
        mailAddressesToAdd.Where(ma => IsValidEmailId(ma));

    foreach (string mailAddressToAdd in validMailAddressesToAdd)
    {
        mailAddresses.Add(mailAddressToAdd);
    }
}