我的方法“ SendMailByAttach”无法按预期工作

时间:2018-12-24 08:58:20

标签: c# asp.net-mvc

我有一个SendMail操作方法和一个SendMailByAttach方法,但是我不知道为什么我的SenMailByAttach方法不能正常工作并且会被捕获,我设置了enable ssl和.. 。但是它不起作用!

我的SendMail操作方法可以正常工作,但是我认为我的问题出在SendMailByAttach方法中,我可以用html正确获取输入信息:

public static bool SendMailByAttach(string subject, string body, string attachment, params string[] toMails)
{
    try
    {
        var mailMsg = new MailMessage();
        mailMsg.BodyEncoding = Encoding.UTF8;
        mailMsg.HeadersEncoding = Encoding.UTF8;
        mailMsg.SubjectEncoding = Encoding.UTF8;
        mailMsg.Priority = MailPriority.High;
        mailMsg.Subject = subject;
        mailMsg.Body = body;
        mailMsg.IsBodyHtml = true;
        mailMsg.From = new MailAddress("maxspeed201@gmail.com", "مهران ", Encoding.UTF8);
        mailMsg.Sender = new MailAddress("maxspeed201@gmail.com", "مهران ", Encoding.UTF8);
        mailMsg.Attachments.Add(new Attachment(attachment));
        foreach (var mail in toMails)
        {
            mailMsg.To.Add(new MailAddress(mail));
        }
        var smtp = new SmtpClient("smtp.gmail.com", 587);
        smtp.UseDefaultCredentials = false;
        smtp.EnableSsl = true;
        smtp.Timeout = 1000;
        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtp.Credentials = new NetworkCredential("MyEmail", "MyPasswordEmail");
        smtp.Send(mailMsg);
        return true;
    }
    catch
    {
        return false;
    }
}

这是我的操作方法:

public ActionResult SendMail(string recivers, string title, string text, HttpPostedFileBase attachment)
{
    bool result = false;
    if (attachment != null)
    {
        string path = Server.MapPath("~") + "\\Files\\Attachment\\" + Path.GetFileName(attachment.FileName);
        attachment.SaveAs(path);                
        //az ultility sendemailbyAttachment etefade kardim
        result = MailSender.SendMailByAttach(title, text, path, recivers.Split(','));
    }
    else
    {
        result = MailSender.SendMail(title, text, recivers.Split(','));
    }
    if (result)
    { //Success in sending
        return MessageBox.Show("پیام با موفقیت ارسال شد", MessageType.Success);
    }
    else
    {
        return MessageBox.Show("پیام ارسال نشد", MessageType.Error);
    }
}

我的SendMailByAttach方法将会流行

1 个答案:

答案 0 :(得分:0)

您可能正在尝试在本地主机中使用gmail发送电子邮件,如果是这种情况,请登录要发送电子邮件的Google帐户,然后转到this链接并允许安全性较低的应用。

如果您在远程服务器上遇到问题,则必须禁用“ Captcha”,并需要通过访问上述链接来允许安全性较低的应用程序。要禁用“验证码”,请转到this链接。

希望这会有所帮助。