send view in email body mvc - asp.net-mvc

I want to send a view in email body in mvc.
please guide how to render view so that it can be sent as html email body.
thanks,

Consider using something like ActionMailer. You can download it using NuGet.

string path = ConfigurationManager.AppSettings["ProjectPath"] ;
string gmailpath = path + "/" + "Driver/VerificedAccount?code=" + root.Result.EmailVerificationCode;
var body= "<html><body><p></p><p><a href = "+gmailpath+" > Please click Verifed Account </a></p></body></html> ";
var st = EmailclassHtml(sendemail.Email, "Verification-Driver", body);
public string EmailclassHtml(string email, string subjectname, string messgae)
{
string ownemail = ConfigurationManager.AppSettings["SenderEmail"];
string ownname = ConfigurationManager.AppSettings["SenderName"];
string returnmessage = "success";
var senderEmail = new MailAddress(ownemail, ownname);
var receiverEmail = new MailAddress(email, "Receiver");
var password = ConfigurationManager.AppSettings["SenderPassword"];
var sub = subjectname;
var body = messgae;
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = true,
Credentials = new NetworkCredential(senderEmail.Address, password)
};
using (var mess = new MailMessage(senderEmail, receiverEmail)
{
Subject = sub,
Body = body,
IsBodyHtml = true
})
try
{
smtp.Send(mess);
return returnmessage;
}
catch (Exception)
{
returnmessage = "fail";
}
return returnmessage;
}

Related

How to change email file's extension?

I am using this class to send an email with a PDF attachment. The class has the following code:
using System.IO;
using System.Net;
using System.Net.Mail;
using DevExpress.XtraPrinting;
using DevExpress.XtraReports.Web.WebDocumentViewer;
using DevExpress.XtraReports.Web.WebDocumentViewer.DataContracts;
namespace DocumentOperationServiceSample.Services
{
public class CustomDocumentOperationService : DocumentOperationService {
public override bool CanPerformOperation(DocumentOperationRequest request)
{
return true;
}
public override DocumentOperationResponse PerformOperation(DocumentOperationRequest request, PrintingSystemBase initialPrintingSystem, PrintingSystemBase printingSystemWithEditingFields)
{
using (var stream = new MemoryStream()) {
printingSystemWithEditingFields.ExportToPdf(stream);
stream.Position = 0;
var mailAddress = new MailAddress(request.CustomData);
var recipients = new MailAddressCollection() { mailAddress };
var attachment = new Attachment(stream, System.Net.Mime.MediaTypeNames.Application.Pdf);
return SendEmail(recipients, "Enter_Mail_Subject", "Enter_Message_Body", attachment);
}
}
DocumentOperationResponse SendEmail(MailAddressCollection recipients, string subject, string messageBody, Attachment attachment) {
string SmtpHost = null;
int SmtpPort = -1;
if (string.IsNullOrEmpty(SmtpHost) || SmtpPort == -1) {
return new DocumentOperationResponse { Message = "Please configure the SMTP server settings." };
}
string SmtpUserName = "Enter_Sender_User_Account";
string SmtpUserPassword = "Enter_Sender_Password";
string SmtpFrom = "Enter_Sender_Address";
string SmtpFromDisplayName = "Enter_Sender_Display_Name";
using (var smtpClient = new SmtpClient(SmtpHost, SmtpPort))
{
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
if (!string.IsNullOrEmpty(SmtpUserName))
{
smtpClient.Credentials = new NetworkCredential(SmtpUserName, SmtpUserPassword);
}
using (var message = new MailMessage())
{
message.Subject = subject.Replace("\r", "").Replace("\n", "");
message.IsBodyHtml = true;
message.Body = messageBody;
message.From = new MailAddress(SmtpFrom, SmtpFromDisplayName);
foreach (var item in recipients)
{
message.To.Add(item);
}
try
{
if (attachment != null)
{
message.Attachments.Add(attachment);
}
smtpClient.Send(message);
return new DocumentOperationResponse
{
Succeeded = true,
Message = "Mail was sent successfully"
};
}
catch (SmtpException e)
{
return new DocumentOperationResponse
{
Message = "Sending an email message failed."
};
}
finally
{
message.Attachments.Clear();
}
}
}
}
protected string RemoveNewLineSymbols(string value)
{
return value;
}
}
}
It works fine, but when I receive the email it has attached an document named application/pdf.
I was trying to find out where the document's name comes from. As you can see in the below image, when I add the application type PDF, it appears exactly what I get attached in email.
The problem is that application/pdf cannot be opened with any PDF viewer app. I have to rename the document to application.pdf in order to be able to open it. Is there a way to change application/pdf with application.pdf?
If anyone is looking for the answer:
var attachment = new Attachment(stream, "report.pdf ", System.Net.Mime.MediaTypeNames.Application.Pdf);

MS Graph SendMail with attachment

I have problem to send an email with attachment.
Without attachment it works.
If I use the same function and add an attachment to the message I get the following error message:
Code: ErrorRequiredPropertyMissing Message: Required property is missing. ClientRequestId: 2af....
I am using MS Graph v4.0.30319
What am I doing wrong
public static async Task<String> SendMyMailAsync()
{
try
{
var FromSender = new Microsoft.Graph.Recipient()
{
EmailAddress = new Microsoft.Graph.EmailAddress
{
Address = "EarlyBird#mail.com"
}
};
byte[] contentBytes = System.IO.File.ReadAllBytes(#"C:\Users\me\Desktop\Test.pdf");
String bs64 = Convert.ToBase64String(contentBytes);
var attachment = new FileAttachment
{
AdditionalData = new Dictionary<string, object>()
{
{"#odata.type","#microsoft.graph.fileAttachment"}
},
//ODataType = "#microsoft.graph.fileAttachment",
ContentType = "application/pdf",
Name = "Test.pdf",
ContentBytes = Convert.FromBase64String(bs64),
IsInline = false,
Size = bs64.Length,
ContentId = "TestMail",
LastModifiedDateTime = DateTime.Now,
Id = "HSDJHEWuDSjfkkfGt",
};
Microsoft.Graph.Message message = new Microsoft.Graph.Message
{
Sender = FromSender,
From = FromSender,
Subject = "Mail no1",
Importance = Microsoft.Graph.Importance.Normal,
Body = new Microsoft.Graph.ItemBody
{
ContentType = Microsoft.Graph.BodyType.Html,
Content = "Hello World",
},
ToRecipients = new List<Microsoft.Graph.Recipient>()
{
new Microsoft.Graph.Recipient
{
EmailAddress = new Microsoft.Graph.EmailAddress
{
Address = "EarlyBird#MailNo2.com"
}
}
},
Attachments = new MessageAttachmentsCollectionPage(),
};
// -- If I comment this out I can send the mail without error but without attachment----
message.Attachments.Add(attachment);
message.HasAttachments = true;
//-----------------------------------------------------------------
var request = graphClient.Me.SendMail(message, true);
// Messages[message.Id].Send();// SendMail(message, null);
await request.Request().PostAsync();
return "Mail send OK";
}
catch (ServiceException ex)
{
Console.WriteLine($"Error getting events: {ex.Message}");
return "Send mail error";
}
}
The below code works perfectly fine for me
public static async Task<String> SendMyMailAsync()
{
try
{
var FromSender = new Microsoft.Graph.Recipient()
{
EmailAddress = new Microsoft.Graph.EmailAddress
{
Address = "Shiva#nishantsingh.live"
}
};
byte[] contentBytes = System.IO.File.ReadAllBytes(#"C:\Users\Shiva\Desktop\sample.pdf");
String bs64 = Convert.ToBase64String(contentBytes);
var attachment = new FileAttachment
{
AdditionalData = new Dictionary<string, object>()
{
{"#odata.type","#microsoft.graph.fileAttachment"}
},
ContentType = "application/pdf",
Name = "Test.pdf",
ContentBytes = Convert.FromBase64String(bs64),
IsInline = false,
Size = bs64.Length,
ContentId = "TestMail",
LastModifiedDateTime = DateTime.Now,
Id = "HSDJHEWuDSjfkkfGt",
};
Microsoft.Graph.Message message = new Microsoft.Graph.Message
{
Sender = FromSender,
From = FromSender,
Subject = "Mail no1",
Importance = Microsoft.Graph.Importance.Normal,
Body = new Microsoft.Graph.ItemBody
{
ContentType = Microsoft.Graph.BodyType.Html,
Content = "Hello World",
},
ToRecipients = new List<Microsoft.Graph.Recipient>()
{
new Microsoft.Graph.Recipient
{
EmailAddress = new Microsoft.Graph.EmailAddress
{
Address = "Shiva#nishantsingh.live"
}
}
},
Attachments = new MessageAttachmentsCollectionPage(),
};
message.HasAttachments = true;
message.Attachments.Add(attachment);
var request = graphClient.Me.SendMail(message, true);
await request.Request().PostAsync();
return "Mail send OK";
}
catch (ServiceException ex)
{
Console.WriteLine($"Error getting events: {ex.Message}");
return "Send mail error";
}
}
You need to make sure that you have the PDF file path correctly specified and the fromSender variable will obviously be yours as you are calling me/sendMail. If you want to send mail from other user's mailbox then you need to have client credential flow setup so that it can give you an App-only token which should have required permissions and you need to change the call something like this var request = graphClient.Users["userid/UPN"].SendMail(message, true);.
I have just updated the MS Graph preview version from
4.0.0-preview.1
to
4.0.0-preview.2
Now everything works as expected
I think it was a bug in preview.1

Emailing recurring invoices using quartz.net in asp.net mvc

I am working on asp.net MVC application that needs to email recurring invoices to customers, i am trying to use quartz.net. I have to email invoice as attachment to every customer on certain date once in the month. I can send email with Quartz without attachments, but when i add attachment it doesn't send, when i click button that is linked with emailing method it does send email to every customers with the invoice attachment. Schedule emails are stored in database and invoices are generated in PDF using Rotativa. Here is my code:
public class Jobclass : IJob
{
public void Execute(IJobExecutionContext context)
{
InvoiceAddlinesController sche = new InvoiceAddlinesController();
sche.Recurring();
}
}
public void Recurring()
{
int originalId = 0;
string companyname = "";
int suc = 0;
string userloggedin = "";
string loggedemail = "";
string password = "";
string Subject = "";
string Message = "";
string bar = "";
string countDown = "";
int seconds = 10;
decimal? totalamount = 0;
var scheduling = from e in db.Invoices
where e.schedule == "Schedule"
select e;
var sched = scheduling.ToList();
foreach (var y in sched)
{
companyname = y.SchedCompanyname;
originalId = y.SchedCustomerId;
loggedemail = y.SchedLoggedemail;
password = y.SchedPassword;
userloggedin = y.SchedRt;
totalamount = y.SchedTotal;
Subject = y.SchedSubject;
Message = y.SchedMassage;
bar = loggedemail.ToString();
bar.Split(';');
using (var message = new MailMessage("myemail#gmail.com", bar))
{
var roata = from e in db.InvoiceAddlines
where e.AddlineID == originalId && e.userId == userloggedin
select e;
var roatainum = roata.ToList();
var model = roatainum;
message.Subject = "Message Subject test";
message.Body = "Message body test at " + DateTime.Now;
var pdf = new ViewAsPdf2("Gem", model, ViewBag.ind = originalId, TempData["user"] = userloggedin);
byte[] pdfByteArray = pdf.GetByte(ControllerContext);
message.IsBodyHtml = true;
MemoryStream file = new MemoryStream(pdfByteArray);
file.Seek(0, SeekOrigin.Begin);
Attachment data = new Attachment(file, "Invoice_Attachment.pdf", "application/pdf");
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.DateTime.Now;
disposition.ModificationDate = System.DateTime.Now;
disposition.DispositionType = DispositionTypeNames.Attachment;
message.Attachments.Add(data);
using (SmtpClient client = new SmtpClient
{
EnableSsl = true,
Host = "smtp.gmail.com",
Port = 587,
Credentials = new NetworkCredential("myemail#gmail.com", "#P#iop234")
})
{
client.Send(message);
}
}
}
}
I have no idea what i am doing wrong.

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);

To send email through mvc3 application

I'm using MVC3 and need to send an email to a user. I don't want to use a gmail server. But, I do want to use server 10.1.70.100. I don't understand what I am doing wrong. Here is my code:
var fromAddress = new MailAddress("sum1#abc.com", "From Name"); var toAddress = new MailAddress(EmailID, "To Name");
const string fromPassword = "";//To be Filled
const string subject = "Verification Mail";
string body = "You have successfully registered yourself. Please Enter your Verification code " + code.ActivatedCode;
var smtp = new SmtpClient
{
Host = "10.1.70.100",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential(),
Timeout = 100000
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
Can someone suggest a way through which I don't have to give my credentials??
I prefer doing this on the following way:
Web.config:
<system.net>
<mailSettings>
<smtp from="Description">
<network host="your.smtpserver" password="" userName="" />
</smtp>
</mailSettings>
</system.net>
Your code:
var smtpClient = new SmtpClient();
smtpClient.Send(mail);
For our OSS project we use this little helper. Hope it helps.
public void SendEmail(string address, string subject, string message)
{
string email = ConfigurationManager.AppSettings.Get("email");
string password = ConfigurationManager.AppSettings.Get("password");
string client = ConfigurationManager.AppSettings.Get("client");
string port = ConfigurationManager.AppSettings.Get("port");
NetworkCredential loginInfo = new NetworkCredential(email, password);
MailMessage msg = new MailMessage();
SmtpClient smtpClient = new SmtpClient(client, int.Parse(port));
msg.From = new MailAddress(email);
msg.To.Add(new MailAddress(address));
msg.Subject = subject;
msg.Body = message;
msg.IsBodyHtml = true;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(msg);
}

Resources