简体   繁体   English

ASP.NET Core 3 传递电子邮件列表以发送方法 Mailkit

[英]ASP.NET Core 3 Passing List of Emails to Send Method Mailkit

I'm using MailKit to send emails for account confirmation and password reset.我正在使用 MailKit 发送电子邮件以进行帐户确认和密码重置。 These operations work as intended, but now I'm trying to modify the same code to also send email notifications to all registered users but this is where I'm having issues.这些操作按预期工作,但现在我正在尝试修改相同的代码,以便向所有注册用户发送电子邮件通知,但这就是我遇到问题的地方。

I've built a List collection using the following code:我使用以下代码构建了一个 List 集合:

public List<string> UserList {
    get {
        var allUsers = userManager.Users;
        return allUsers.Select(x => x.Email).ToList();
    }
}

this collection returns all emails within my AspNetUsers table successfully.此集合成功返回我的 AspNetUsers 表中的所有电子邮件。

Next I create 3 variables:接下来我创建 3 个变量:

var toAddress = UserList;
var subject = "New Asset Added" + " " + model.Name;
var body = model.Name + model.AssetType + model.AssetURL;

When debugging and stepping through the code I do see Count = 2 and then the list of emails in the variable.在调试和单步执行代码时,我确实看到了Count = 2 ,然后是变量中的电子邮件列表。 So far this looks good到目前为止,这看起来不错

After the 3 variables I have this line of code that passes the collected information to the Send method:在 3 个变量之后,我有这行代码将收集到的信息传递给 Send 方法:

_emailSender.Send(toAddress[0], subject, body);

Again, the toAddress[0] when stepping through code shows Count = 2 so I'm assuming the way I have it written is valid.同样,逐步执行代码时的toAddress[0]显示Count = 2所以我假设我编写它的方式是有效的。

Once I reach the Send Method code and I check the toAddress variable again, it is now stripped of the Count = 2 and becomes just the first email address in the list which makes sense since I passed the variable with an index of 0. What I really need is to pass all emails not just 1.一旦我到达 Send Method 代码并再次检查toAddress变量,它现在被剥离了Count = 2并成为列表中的第一个电子邮件地址,这很有意义,因为我传递了索引为 0 的变量。我是什么真正需要的是传递所有电子邮件,而不仅仅是 1。

If I remove the brackets or leave the brackets empty I get an error:如果我删除括号或将括号留空,则会出现错误:

cannot convert from 'System.Collections.Generic.List<string>' to 'string'

So for now I'm forced to add an index.所以现在我被迫添加一个索引。

My send method seems fairly simple but I do believe my foreach loop might also not be well formulated.我的发送方法看起来相当简单,但我相信我的 foreach 循环也可能没有很好地制定。 Here's my Send Method in it's entirety.这是我的发送方法的完整内容。

public async void Send(string toAddress, string subject, string body, bool sendAsync = true) {
    var mimeMessage = new MimeMessage(); // MIME : Multipurpose Internet Mail Extension
    mimeMessage.From.Add(new MailboxAddress(_fromAddressTitle, _fromAddress));

    foreach (char toAddresses in toAddress) {
        mimeMessage.To.Add(new MailboxAddress(toAddresses)); //I get error saying cannot convert char to string.  
    }

    mimeMessage.Subject = subject;

    var bodyBuilder = new MimeKit.BodyBuilder {
        HtmlBody = body
    };

    mimeMessage.Body = bodyBuilder.ToMessageBody();

    using (var client = new MailKit.Net.Smtp.SmtpClient()) {
        client.Connect(_smtpServer, _smtpPort, _enableSsl);

        client.Authenticate(_username, _password); // If using GMail this requires turning on LessSecureApps : https://myaccount.google.com/lesssecureapps
        if (sendAsync) {
            await client.SendAsync(mimeMessage);
        }
        else {
            client.Send(mimeMessage);
        }

        client.Disconnect(true);
    }
}

My end goal is to use a foreach loop on the mimeMessage.To.Add(new MailboxAddress(toAddresses));我的最终目标是在mimeMessage.To.Add(new MailboxAddress(toAddresses));上使用 foreach 循环mimeMessage.To.Add(new MailboxAddress(toAddresses)); so that everyone can receive an email if there is more than 1 email address, if not it can loop once.这样每个人都可以在电子邮件地址超过 1 个的情况下收到一封电子邮件,否则可以循环一次。

Thanks in advance!提前致谢!

In your method, Send() , you are taking in a string for toAddress and then splitting its characters... that wont work.在您的方法Send() ,您正在为 toAddress 输入一个字符串,然后拆分其字符......这是行不通的。 If you want to to use one or more email addresses, you will need to send in email address(es) separated by a delimiter or as a complete list.如果您想使用一个或多个电子邮件地址,您需要以分隔符或完整列表的形式发送电子邮件地址。

Two ways to go about it.有两种方法可以解决。

Change the argument from string to List将参数从字符串更改为列表

  1. change your method to take in a List更改您的方法以获取列表
public async void Send(List<string> toAddress, string subject, string body, bool sendAsync = true)
{
    var mimeMessage = new MimeMessage(); // MIME : Multipurpose Internet Mail Extension
    mimeMessage.From.Add(new MailboxAddress(_fromAddressTitle, _fromAddress));

    toAddress.ForEach(address => mimeMessage.To.Add(new MailboxAddress(address)));
...

if you use this method, you will need to send in the list as well.. not a single email address string.如果您使用此方法,您还需要发送列表......而不是单个电子邮件地址字符串。

List<string> toAddress = new List<string>() { "firstEmail", "Second" ...};
_emailSender.Send(toAddress, subject, body);

// You will not be able to do send in single string
_emailSender.Send("firstemail@only.com", subject, body); //Exception no method found.

Send in a delimited list发送分隔列表

  1. Always send in comma separated email addresses and translate those to multiple addresses when adding them to To field of your mimeMessage.始终以逗号分隔的电子邮件地址发送,并将它们添加到 mimeMessage 的 To 字段时将它们转换为多个地址。
public async void Send(string toAddress, string subject, string body, bool sendAsync = true)
{
    var mimeMessage = new MimeMessage(); // MIME : Multipurpose Internet Mail Extension
    mimeMessage.From.Add(new MailboxAddress(_fromAddressTitle, _fromAddress));

    // HERE -> FOREACH string, not char.
    foreach (string toAddresses in toAddress.Split(',')) // Split on ,
    {
        mimeMessage.To.Add(new MailboxAddress(toAddresses)); 
    }

and you will need to use this method the following way...并且您需要按以下方式使用此方法...

List<string> toAddress = new List<string>() {"first", "..."};
_emailSender.Send(string.Join(',',toAddress), subject, body);

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

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