简体   繁体   English

Asp.Net-身份2-在EmailService触发的电子邮件中附加文件

[英]Asp.Net - Identity 2 - Attach files in emails fired by EmailService

I´m using Asp.Net-Identity-2 to manage user access in my app. 我正在使用Asp.Net-Identity-2在我的应用程序中管理用户访问。

I´m using EmailService (UserManager.SendEmail) to send confirmation email messages and I´d like to send a formatted HTML message, and I want attach images in it. 我正在使用EmailService(UserManager.SendEmail)发送确认电子邮件,并且希望发送格式化的HTML消息,我想在其中附加图像。

How can I do that?? 我怎样才能做到这一点??

  • Setup Identity User Manager EmailService 设置身份用户管理器EmailService

     public class AppUserManager : UserManager<AppUser> { public AppUserManager(IUserStore<AppUser> store) : base(store) { } public static AppUserManager Create(IdentityFactoryOptions<AppUserManager> options, IOwinContext context) { AppUserManager manager = new AppUserManager(new UserStore<AppUser>(db)); //Some setup code here .... //Hook to my EmailService (see class MyEmailService.cs) manager.EmailService = new MyEmailService(); return manager; } //Create } //class 
  • MyEmailService MyEmailService

     public class MyEmailService : IIdentityMessageService { public Task SendAsync(IdentityMessage message) { MailMessage email = new MailMessage("me@sample.com", message.Destination); email.Subject = message.Subject; email.Body = message.Body; email.IsBodyHtml = true; var mailClient = new SmtpClient(); mailClient.Host = "EmailServer"; mailClient.Port = 25; return mailClient.SendMailAsync(email); } //SendAsync } //class 
  • Action to send email 发送电子邮件的动作

     public ActionResult ForgotPassword(string email) { if (ModelState.IsValid) { AppUser user = UserManager.FindByEmail(email); if (user == null || !(UserManager.IsEmailConfirmed(user.Id))) { return View("../Home/Index"); } //if string code = UserManager.GenerateEmailConfirmationToken(user.Id); string callbackUrl = Url.Action("ResetPassword", "Admin", new { Id = user.Id, code = code }, protocol: Request.Url.Scheme); string strMessage = getHTMLMessage(); //variable Html message here, with images references in it (ex. "<img src='cid:IMAGE_TITLE'>") UserManager.SendEmail(user.Id, "Message Subject", strMessage); return View("../Home/Index"); } // If we got this far, something failed, redisplay form return View(); } //ForgotPassword 

My doubt is how to attach images in that message... 我的疑问是如何在该邮件中附加图片...

Thanks for any help.. 谢谢你的帮助..

Julio Schurt 朱利奥·舒尔特

I had to create another method in my service and call it directly 我必须在服务中创建另一个方法并直接调用它

    public Task SendAsync(IdentityMessage message, IEnumerable<KeyValuePair<string, Stream>> attach)
    {
        var myMessage = new SendGridMessage() { From = new MailAddress("my@email.com") };
        myMessage.AddTo(message.Destination);
        myMessage.Subject = message.Subject;

        myMessage.Html = message.Body;
        myMessage.Text = message.Body;


        var credentials = new NetworkCredential("myuser", "mypassword");
        var transportWeb = new Web(credentials);

        foreach (var file in attach)
        {
            myMessage.AddAttachment(file.Value,file.Key);
        }

        return transportWeb.DeliverAsync(myMessage);
    }

EDIT: (2015-08-14) 编辑:(2015-08-14)

Final class: 期末课程:

public class EmailService : IIdentityMessageService
{
    const string from = "mail@domain.com";
    const string username = "username";//Environment.GetEnvironmentVariable("SENDGRID_USER");
    const string pswd = "password";//Environment.GetEnvironmentVariable("SENDGRID_PASS");
    private List<KeyValuePair<string, Stream>> _attachments;
    private List<KeyValuePair<string, string>> _recipients;

    public Task SendAsync(IdentityMessage message)
    {
        var myMessage = new SendGridMessage() { From = new MailAddress(from) };
        var credentials = new NetworkCredential(username, pswd);
        var transportWeb = new Web(credentials);

        myMessage.AddTo(message.Destination);
        if (_recipients != null)
        {
            _recipients.ForEach(r => myMessage.AddTo(string.Format("{0} {1}", r.Key, r.Value)));
        }
        myMessage.Subject = message.Subject;
        myMessage.Html = message.Body;
        myMessage.Text = message.Body;

        if (_attachments != null)
        {
            foreach (var attachment in _attachments)
            {
                myMessage.AddAttachment(attachment.Value, attachment.Key);
            }
        }

        return transportWeb.DeliverAsync(myMessage);
    }

    public Task SendAsync(IdentityMessage message, IEnumerable<KeyValuePair<string, Stream>> attachments)
    {
        var myMessage = new SendGridMessage() { From = new MailAddress(from) };
        var credentials = new NetworkCredential(username, pswd);
        var transportWeb = new Web(credentials);

        myMessage.AddTo(message.Destination);
        myMessage.Subject = message.Subject;
        myMessage.Html = message.Body;
        myMessage.Text = message.Body;

        foreach (var attachment in attachments)
        {
            myMessage.AddAttachment(attachment.Value, attachment.Key);
        }

        return transportWeb.DeliverAsync(myMessage);
    }

    public Task SendAsync(IdentityMessage message, KeyValuePair<string, Stream> attachment)
    {
        var myMessage = new SendGridMessage() { From = new MailAddress(from) };
        var credentials = new NetworkCredential(username, pswd);
        var transportWeb = new Web(credentials);

        myMessage.AddTo(message.Destination);
        myMessage.Subject = message.Subject;
        myMessage.Html = message.Body;
        myMessage.Text = message.Body;
        myMessage.AddAttachment(attachment.Value, attachment.Key);

        return transportWeb.DeliverAsync(myMessage);
    }

    public void AddTo(string name,string mail)
    {
        _recipients = _recipients ?? new List<KeyValuePair<string, string>>();
        _recipients.Add(new KeyValuePair<string, string>(name, string.Format("<{0}>", mail)));
    }

    public void AddAttachment(string name, Stream file)
    {
        _attachments = _attachments ?? new List<KeyValuePair<string, Stream>>();
        _attachments.Add(new KeyValuePair<string, Stream>(name, file));
    }

    public void AddAttachment<T>(string name, T records)
    {
        var jsonSerialiser = new JavaScriptSerializer();
        var json = jsonSerialiser.Serialize(records);
        var bytes = Encoding.UTF8.GetBytes(json);
        var ms = new MemoryStream(bytes);
        ms.Flush();
        ms.Seek(0, SeekOrigin.Begin);


        _attachments = _attachments ?? new List<KeyValuePair<string, Stream>>();
        _attachments.Add(new KeyValuePair<string, Stream>(name, ms));
    }
}

Then can use it... 然后可以使用它...

// use it directly
                var emailService = new EmailService();
                IdentityMessage msg = new IdentityMessage()
                {
                    Destination = "test <test@domain.com>",
                    Subject = "Subject",
                    Body = "Body"
                };

                emailService.AddTo("Name1", "mail1@domain.com");
                emailService.AddTo("Name2", "mail2@domain.com");
                emailService.AddTo("Name3", "mail3@domaincom");

                emailService.AddAttachment(filename", stream);
                await emailService.SendAsync(msg);

                // Or use it from UserManager
                (UserManager.EmailService as EmailService).AddAttachment("name", yourStream);
                await UserManager.SendEmailAsync("userid", "subject", "body");

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

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