MVC system.net.mail - asp.net-mvc

Hi I am having difficulties sending email to registered users.I get exception error in the line:
msg.To.Add(new MailAddress(newsletter.AspNetUser.Email));
Error:
An exception of type 'System.NullReferenceException' occurred in MVCHarmony.dll but was not handled in user code
Additional information: Object reference not set to an instance of an object.
Following is my code.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "NewsLetterId,Headerline,Description,Photo,NewsletterFile,Id")] Newsletter newsletter, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
MailMessage msg = new MailMessage();
SmtpClient smtp = new SmtpClient();
StringBuilder sb = new StringBuilder();
msg.From = new MailAddress("abc#hotmail.com");
msg.To.Add(new MailAddress(newsletter.AspNetUser.Email));
msg.Subject = "Newsletter";
if (file != null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
var attachment = new Attachment(file.InputStream, fileName);
msg.Attachments.Add(attachment);
}
msg.IsBodyHtml = false;
sb.Append("" + newsletter.Headerline);
sb.Append(Environment.NewLine);
sb.Append("" + newsletter.Description);
sb.Append(Environment.NewLine);
msg.Body = sb.ToString();
smtp.Host = "smtp.live.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("abc#hotmail.com", "*******");
smtp.Send(msg);
db.Newsletters.Add(newsletter);
db.SaveChanges();
msg.Dispose();

Related

.net mvc SendAsync - How to find error logs if a message can't be sent?

I have the following class to send emails.
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
if (message != null)
{
MailMessage mail = new MailMessage();
mail.To.Add(message.Destination);
mail.From = new MailAddress("test#test.com");
mail.Subject = message.Subject;
string Body = message.Body;
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.test.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
//
smtp.Credentials = new System.Net.NetworkCredential("username", "pass");
smtp.EnableSsl = true;
return smtp.SendMailAsync(mail);
}
return Task.FromResult(0);
}
}
Our IT informed us that he open the port 587 on the firewall. However, the emails can't be sent.
In C:\inetpub\logs\LogFiles\W3SVC2 logs I have the following messages without getting an error.
2021-02-08 12:02:13 192.168.1.2 GET /signalr/connect transport=serverSentEvents&clientProtocol=1.5&connectionToken=1%2FM7LMZNVeWfN1mD1D9geTBdC7vVjo6nQRtD%2BrQv%2BVwUUdC6eE6jbKaIq2CUlrUsaylRVyJgz6fFqoQDsxJ9%2F77L8kizNCyZYkAs5nxK2T6Crz4xlKu9lAS1z9%2FHDen84sd7IVBASCnCm46jfQlrdg%3D%3D&connectionData=%5B%7B%22name%22%3A%22chathub%22%7D%5D&tid=0 81 test#gmail.com 192.168.1.1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/88.0.4324.146+Safari/537.36 http://192.168.1.2:81/Account/ReSendEmailConfirmationTokenAsync?userID=51abfa03-6d09-40bb-8e4c-89117515ff&subject=Confirm%20your%20account 200 0 0 494899
Can you please help me?

How can I send an email to specific email-id in asp.net mvc?

System.IO.StringWriter myStringWriter = new System.IO.StringWriter(new System.Text.StringBuilder());
HtmlTextWriter myTextWriter = new HtmlTextWriter(myStringWriter);
StringBuilder sb = new StringBuilder();
sb.Append("Hello");
string Body= sb.ToString();
MailMessage myMessage = new MailMessage();
myMessage.To.Add("edf#gmail.com");
myMessage.Subject = "Registration Successfully Completed";
myMessage.Body = Body;
myMessage.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient())
{
//smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("abc#gmail.com", "abc#46");
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = true;
smtp.EnableSsl = true;
smtp.Send(myMessage);
}
I am getting this error:
The SMTP server requires a secure connection or the client was not
authenticated. The server response was: 5.5.1 Authentication Required.
Learn more at

Mail pdf Attachment using Rotativa

Sending the email and the attachment actaly works. my issue is i get this error when trying to send the "generated pdf"
An exception of type 'System.Exception' occurred in Rotativa.dll but was not handled in user code
Additional information: Error: Failed loading page http://localhost:49224/Offer/OfferPdf/4 (sometimes it will work just to ignore this error with --load-error-handling ignore)
The mail test in the controller:
public ActionResult MailTest()
{
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress(CoEmail));
msg.From = new MailAddress(MailFrom, UserName);
msg.Subject = "Offer";
msg.Body = "This is a Test";
MemoryStream stream = new MemoryStream(OffersPdfMail (4, "Offer"));
Attachment att1 = new Attachment(stream, "Offer.pdf", "application/pdf");
msg.Attachments.Add(att1);
msg.IsBodyHtml = true;
msg.BodyEncoding = System.Text.Encoding.UTF8;
msg.SubjectEncoding = System.Text.Encoding.Default;
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(User, Pass);
client.Port = 587; //
client.Host = "smtp.office365.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
try
{
client.Send(msg);
return RedirectToAction("index");
}
catch (Exception ex)
{
return HttpNotFound();
}
}
The Byte[]:
public Byte[] OfferPdfMail(int? id, string filename)
{
var mailpdft = new ActionAsPdf("OfferPdf/4")
{
FileName = "Offer",
PageSize = Rotativa.Options.Size.A4,
PageWidth = 210,
PageHeight = 297
};
Byte[] PdfData = mailpdft.BuildPdf(ControllerContext);
return PdfData;
and last the ViewasPdf:
public ActionResult OfferPdf (int? id, string filename)
{
string footer = "test" ;
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var pdf = new ViewAsPdf("TilbudsPdf") {
FileName = filename,
PageSize = Rotativa.Options.Size.A4,
PageOrientation = Rotativa.Options.Orientation.Portrait,
PageMargins = new Rotativa.Options.Margins(12, 12, 12, 12),// it’s in millimeters
PageWidth = 210,
PageHeight = 297,
CustomSwitches = footer };
return pdf;
}
Editted the names to english. may have missed some.
Thanks for your patience, and sorry for the bad english.
Best regards Eric
I found an solution, it was because i was stupid trying to making an pdf of a pdf. so i made a new ActionResult method like this:
public ActionResult tilbudspdfMailView(int? id, string filename)
{
Offer Offer= db.Offer.Find(id);
return View("OfferPdf", Offer);
}

ASP.Net MVC File Upload and Attach to Email

I'm developing an ASP.Net MVC 3 web application. One of my Razor Views allows a user to upload a file (selected from their computer) and then this is attached to an outgoing email.
Below is my code to date, but unfortunately it does not work. By this I mean the email (and of course the attachment) never gets sent. Although, when I step threw/ debug my code locally no errors occur, and none as well on the live server.
Does anyone see what I'm missing? Any advice would be greatly appreciated.
Thanks.
Controller
[HttpPost]
public ActionResult CvUpload(HttpPostedFileBase file)
{
//Get logged in user
User user = _accountService.GetUser(_formsAuthService.GetLoggedInUserID());
if (file != null && file.ContentLength > 0)
{
_emailService.SendUpload(user, file);
return RedirectToAction("CvUpload", new { feedBack = "Success" });
}
return RedirectToAction("CvUpload", new { feedBack = "Failed" });
}
Email Service
public void SendUpload(User user, HttpPostedFileBase file)
{
string messageBody = "";
string subject = "Upload";
string[] toAddress = new string[1];
string ToBCC = "";
if (isProduction.Equals("true"))
{
toAddress[0] = "myemail#test.com";
sendEmail(toAddress, ToBCC, adminFromEmail, adminFromEmail, subject, messageBody, true, emailServer, file);
}
else
{
// DO NOT SEND EMAIL
}
}
private bool sendEmail(string[] toAddresses, string ToBCC, string fromAddress, string replyto, string subject, string body, bool ishtml, string emailHost, HttpPostedFileBase file)
{
bool mailSent = false;
try
{
MailMessage mail = new MailMessage();
foreach (string addresss in toAddresses)
mail.To.Add(addresss);
mail.From = new MailAddress(fromAddress);
mail.ReplyToList.Add(replyto);
mail.Bcc.Add(ToBCC);
mail.Subject = subject;
mail.Body = body;
if(file != null && file.ContentLength > 0)
{
string fileName = Path.GetFileName(file.FileName);
mail.Attachments.Add(new Attachment(file.InputStream, fileName));
}
if (ishtml)
mail.IsBodyHtml = true;
else
mail.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient();
smtp.Host = emailHost;
smtp.Send(mail);
mailSent = true;
}
catch (Exception)
{
mailSent = false;
}
return mailSent;
}
I have a similar service and this is what I have although the attachments are saved so they can be reused later.
var attachment = new Attachment(path);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(path);
disposition.ModificationDate = File.GetLastWriteTime(path);
disposition.ReadDate = File.GetLastAccessTime(path);
disposition.FileName = attachmentName.Name;
disposition.Size = new FileInfo(path).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
mailMessage.Attachments.Add(attachment);

asp.net mvc send multiple email with different subject and body asynchronously

Folks,
I wanted to send a few emails with different subject and body asynchronously. here is my code
Email.cs
public string To;
public string CC;
public string Subject;
public string Host;
public string Port;
public string Body;
public MailMessage mail;
public SmtpClient smtp;
public void send()
{
smtp = new SmtpClient();
mail = new MailMessage();
mail.To.Add(To);
if (this.CC !="" && this.CC !=null) mail.CC.Add(CC);
mail.CC.Add(CCIDBizzMail);
mail.Subject = this.Subject;
mail.From = new MailAddress(From);
mail.IsBodyHtml = true;
smtp.Host = this.SMTPAddress;
mail.Body = this.Body;
smtp.Credentials = new System.Net.NetworkCredential
(this.From, this.Password);
smtp.EnableSsl = false;
smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
smtp.SendAsync(mail, null);
}
private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
String token = (string)e.UserState;
if (e.Cancelled)
{
}
if (e.Error != null)
{
}
else
{
mail.Dispose();
smtp.Dispose();
}
}
here is my code to send an email:
Email objEmail = new Email();
objEmail.Subject = "Thank You for Your Order!";
objEmail.Body = "first email";
objEmail.To: "ssss#mail.com"
objEmail.Send();
objEmail.Subject = "Thank You for Your Order!";
objEmail.Body = "second email";
objEmail.To: "tttt#mail.com"
objEmail.Send();
However, tttt#mail.com never received an email. my website always send to ssss#mail.com
can you help me to solve this issue?
Here you try to send an email with Asynchronous type with out making a new object Email.
I suggest to try two thinks.
Make new on every email send
{
Email objEmail = new Email();
objEmail.Subject = "Thank You for Your Order!";
objEmail.Body = "first email";
objEmail.To: "ssss#mail.com"
objEmail.Send();
}
{
Email objEmail = new Email();
objEmail.Subject = "Thank You for Your Order!";
objEmail.Body = "second email";
objEmail.To: "tttt#mail.com"
objEmail.Send();
}
Or change the Email routine to
public string To;
public string CC;
public string Subject;
public string Host;
public string Port;
public string Body;
public void send()
{
using(var smtp = new SmtpClient())
{
using(mail = new MailMessage())
{
mail.To.Add(To);
if (this.CC !="" && this.CC !=null) mail.CC.Add(CC);
mail.CC.Add(CCIDBizzMail);
mail.Subject = this.Subject;
mail.From = new MailAddress(From);
mail.IsBodyHtml = true;
smtp.Host = this.SMTPAddress;
mail.Body = this.Body;
smtp.Credentials = new System.Net.NetworkCredential
(this.From, this.Password);
smtp.EnableSsl = false;
// maybe here you place extra code for the errors
// http://msdn.microsoft.com/en-us/library/swas0fwc.aspx
smtp.Send(mail);
}
}
}
If the email is send using localhost and if you like to send many emails, is better to send them right way and not asynchronous.

Resources