i want to send the Email and using smtp class and i want to Cc also but getting Cc is a read only property.my code below
System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage();
MyMailMessage.From = new System.Net.Mail.MailAddress(this.SenderAddress);
MyMailMessage.CC = new System.Net.Mail.MailAddress(this.CcAddress);
string m_CcAddress = null;
public string CcAddress {
get {
return this.m_CcAddress; }
set {
this.m_CcAddress = value;
}
}
Correct, cc is a list, not a String.. So you normally would have
myMailMessage.cc.Add(m_CcAddress);
As demonstrated by Microsoft
Related
I am using Rotativa to convert my view to pdf. I would like to send that generated pdf as an email attachment (without having to download it first to disk). I've been following a bunch of tutorials to do this but I just keep going round in circles. I would much appreciate any help I can get.
public async Task<IActionResult>SomeReport()
{
...
return new ViewAsPdf (report)
}
return view();
MemoryStream memoryStream = new MemoryStream();
MimeMessage msg = new MimeMessage();
MailboxAddress from = new MailboxAddress ("Name", "emailAddress")
msg.From.Add(from);
MailboxAddress to = new MailboxAddress ("Name", "emailAddress")
msg.From.Add(to);
BodyBuilder bd = new BodyBuilder();
bb.HtmlBody ="some text";
bb.Attachments.Add("attachmentName", new MemoryStream());
msg.Body = bb.ToMessageBody();
SmtpClient smtp = new SmtpClient();
smtp.Connect("smtp.gmail.com",465, true);
smtp.Authenticate("emailAddress", "Pwd");
smtp.Send(msg);
smtp.Disconnect(true);
smtp.Dispose();
Edit
Parent View from which Email is sent
#Model MyProject.Models.EntityViewModel
<a asp-action= "SendPdfMail" asp-controller ="Student" asp-route-id = "#Model.Student.StudentId">Email</a>
...
SendPdfMail action in Student Controller
public async Task<IActionResult> SendPdfMail(string id)
{
var student = await context.Student. Where(s => s.StudentId == id);
if (student != null)
{
...
var viewAsPdf = new ViewAsPdf("MyPdfView", new{route = id})
{
Model = new EntityViewModel(),
FileName = PdfFileName,
...
}
}
};
Complete answer using Rotativa.AspNetCore. Code is developed in VS 2019, Core 3.1, Rotativa.AspNetCore 1.1.1.
Nuget
Install-package Rotativa.AspNetCore
Sample controller
public class SendPdfController : ControllerBase
{
private const string PdfFileName = "test.pdf";
private readonly SmtpClient _smtpClient;
public SendPdfController(SmtpClient smtpClient)
{
_smtpClient = smtpClient;
}
[HttpGet("SendPdfMail")] // https://localhost:5001/SendPdfMail
public async Task<IActionResult> SendPdfMail()
{
using var mailMessage = new MailMessage();
mailMessage.To.Add(new MailAddress("a#b.c"));
mailMessage.From = new MailAddress("c#d.e");
mailMessage.Subject = "mail subject here";
var viewAsPdf = new ViewAsPdf("view name", <YOUR MODEL HERE>)
{
FileName = PdfFileName,
PageSize = Size.A4,
PageMargins = { Left = 1, Right = 1 }
};
var pdfBytes = await viewAsPdf.BuildFile(ControllerContext);
using var attachment = new Attachment(new MemoryStream(pdfBytes), PdfFileName);
mailMessage.Attachments.Add(attachment);
_smtpClient.Send(mailMessage); // _smtpClient will be disposed by container
return new OkResult();
}
}
Options class
public class SmtpOptions
{
public string Host { get; set; }
public int Port { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
In Startup#ConfigureServices
services.Configure<SmtpOptions>(Configuration.GetSection("Smtp"));
// SmtpClient is not thread-safe, hence transient
services.AddTransient(provider =>
{
var smtpOptions = provider.GetService<IOptions<SmtpOptions>>().Value;
return new SmtpClient(smtpOptions.Host, smtpOptions.Port)
{
// Credentials and EnableSsl here when required
};
});
appsettings.json
{
"Smtp": {
"Host": "SMTP HOST HERE",
"Port": PORT NUMBER HERE,
"Username": "USERNAME HERE",
"Password": "PASSWORD HERE"
}
}
There's not quite enough to go on, but you need something like this:
MimeMessage msg = new MimeMessage();
MailboxAddress from = new MailboxAddress ("Name", "emailAddress");
msg.From.Add(from);
MailboxAddress to = new MailboxAddress ("Name", "emailAddress");
msg.To.Add(to);
BodyBuilder bb = new BodyBuilder();
bb.HtmlBody ="some text";
using (var wc = new WebClient())
{
bb.Attachments.Add("attachmentName",wc.DownloadData("Url for your view goes here"));
}
msg.Body = bb.ToMessageBody();
using (var smtp = new SmtpClient())
{
smtp.Connect("smtp.gmail.com",465, true);
smtp.Authenticate("emailAddress", "Pwd");
smtp.Send(msg);
smtp.Disconnect(true);
}
Notice this adds the attachment before calling .ToMessageBody(), as well as fixing at least four basic typos.
But I doubt this will be enough... I suspect ViewAsPdf() needs more context than you get from a single DownloadData() request, and you'll need to go back to the drawing board to be able to provide that context, but this at least will help push you in the right direction.
This question already has answers here:
How to send HTML-formatted email? [duplicate]
(3 answers)
Closed 5 years ago.
I am calling a function that sends an email in my asp.net mvc project and I want the body to be able to format as html
Here is my function that sends the email :
private void EnvoieCourriel(string adrCourriel, string text, string object, string envoyeur, Attachment atache)
{
SmtpClient smtp = new SmtpClient();
MailMessage msg = new MailMessage
{
From = new MailAddress(envoyeur),
Subject = object,
Body = text,
};
if (atache != null)
msg.Attachments.Add(atache);
msg.To.Add(adrCourriel);
smtp.Send(msg);
return;
}
The email is sent and it works like a charm, but It just shows plain html so I was wondering an argument in my instanciation of MailMessage
You just need to add the parameter IsBodyHtml to your instanciation of the MailMessage like this :
private bool EnvoieCourriel(string adrCourriel, string corps, string objet, string envoyeur, Attachment atache)
{
SmtpClient smtp = new SmtpClient();
MailMessage msg = new MailMessage
{
From = new MailAddress(envoyeur),
Subject = objet,
Body = corps,
IsBodyHtml = true
};
if (atache != null)
msg.Attachments.Add(atache);
try
{
msg.To.Add(adrCourriel);
smtp.Send(msg);
}
catch(Exception e)
{
var erreur = e.Message;
return false;
}
return true;
}
I also added a try catch because if there is a problem when trying to send the message you can show an error or just know that the email was not sent without making the application crash
I think you are looking for IsBodyHtml.
private void EnvoieCourriel(string adrCourriel, string text, string object, string envoyeur, Attachment atache)
{
SmtpClient smtp = new SmtpClient();
MailMessage msg = new MailMessage
{
From = new MailAddress(envoyeur),
Subject = object,
Body = text,
IsBodyHtml = true
};
if (atache != null)
msg.Attachments.Add(atache);
msg.To.Add(adrCourriel);
smtp.Send(msg);
return;
}
I have 4 elements:
A class EmailGT.cs (for the get and set thing)
A class Email.cs (to actually send the email)
Two other Windows Forms to the user press the button and send the email
I wanted to use get and set to define the message and the person who is going to recieve the email.
I've done this:
class EmailGT
{
private string _mensagem = string.Empty;
private string _destinatario = string.Empty;
public string mensagem
{
get { return _mensagem; }
set { _mensagem = value; }
}
public string destinatario
{
get { return _destinatario; }
set { _destinatario = value; }
}
}
}
In the Email.cs I have this (I didn't post the whole code since it wouldn't be necessary):
class Email
{
public void SendEmail()
{
EmailGT x = new EmailGT();
string destinatario = x.destinatario;
string mensagem = x.mensagem;
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add(destinatario);
message.Subject = "something";
message.Body = mensagem;
And in the Windows Forms (both) I have this:
EmailGT x = new EmailGT();
Email z = new Email();
x.mensagem = "teste 2";
x.destinatario = "my email";
z.SendEmail();
However, both fields go empty on the Email.cs. I guess I didn't really understand how to use this. Can somebody say what is wrong? Thanks!
The EmailGT x in SendEmail has nothing to do with the EmailGT x on which you're setting properties. Perhaps you want to change SendEmail to accept an EmailGT as a parameter:
class Email
{
public void SendEmail(EmailGT x)
{
string destinatario = x.destinatario;
string mensagem = x.mensagem;
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add(destinatario);
message.Subject = "something";
message.Body = mensagem;
// snip
}
}
then you'd pass the EmailGT to SendEmail:
EmailGT x = new EmailGT();
x.mensagem = "teste 2";
x.destinatario = "my email";
Email z = new Email();
z.SendEmail(x);
You should change SendEmail method declaration to take EmailGT instance as a parameter, and use that instance within the method, instead of creating local variable.
public void SendEmail(EmailGT x)
{
string destinatario = x.destinatario;
string mensagem = x.mensagem;
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add(destinatario);
message.Subject = "something";
message.Body = mensagem;
}
And usage:
EmailGT x = new EmailGT();
x.mensagem = "teste 2";
x.destinatario = "my email";
Email z = new Email();
z.SendEmail(x);
I need to send a mail including the exception details (Yellow Screen Of Death) as attachment.
I could get the YSOD as follows:
string YSODmarkup = lastErrorWrapper.GetHtmlErrorMessage();
if (!string.IsNullOrEmpty(YSODmarkup))
{
Attachment YSOD = Attachment.CreateAttachmentFromString(YSODmarkup, "YSOD.htm");
mm.Attachments.Add(YSOD);
}
mm is of type MailMessage, but the mail is not sent.
Here
System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage("from", "to", "Exception-Details", htmlEmail.ToString());
is used to bind the body of the mail.
After this only the attachment is added.
While removing the attachment, mail is sent.
Can anyone help me out?
As per the comments from Mr. Albin and Mr. Paul am updating the following
string YSODmarkup = Ex_Details.GetHtmlErrorMessage();
string p = System.IO.Directory.GetCurrentDirectory();
p = p + "\\trial.txt";
StreamWriter sw = new StreamWriter(p);
sw.WriteLine(YSODmarkup);
sw.Close();
Attachment a = new Attachment(p);
if (!string.IsNullOrEmpty(YSODmarkup))
{
Attachment YSOD = Attachment.CreateAttachmentFromString(YSODmarkup, "YSOD.html");
System.Net.Mail.Attachment(server.mappath("C:\\Documents and Settings\\user\\Desktop\\xml.docx"));
MyMailMessage.Attachments.Add(a);
}
Here i attached the contents to a text file and tried the same. So the mail was not sent. Is there any issue with sending mails which contains HTML tags in it. Because i was able to attach a normal text file.
namespace SendAttachmentMail
{
class Program
{
static void Main(string[] args)
{
var myAddress = new MailAddress("jhered#yahoo.com","James Peckham");
MailMessage message = new MailMessage(myAddress, myAddress);
message.Body = "Hello";
message.Attachments.Add(new Attachment(#"Test.txt"));
var client = new YahooMailClient();
client.Send(message);
}
}
public class YahooMailClient : SmtpClient
{
public YahooMailClient()
: base("smtp.mail.yahoo.com", 25)
{
Credentials = new YahooCredentials();
}
}
public class YahooCredentials : ICredentialsByHost
{
public NetworkCredential GetCredential(string host, int port, string authenticationType)
{
return new NetworkCredential("jhered#yahoo.com", "mypwd");
}
}
}
I'm going through my app, trying to clean up some code that sends e-mails. I started creating my own emailer wrapper class, but then I figured that there must be a standard emailer class out there somewhere. I've done some searching, but couldn't find anything.
Also, is there a code base for stuff like this anywhere?
EDIT: Sorry, let me clarify.
I don't want to have this in my code any time I need to send an e-mail:
System.Web.Mail.MailMessage message=new System.Web.Mail.MailMessage();
message.From="from e-mail";
message.To="to e-mail";
message.Subject="Message Subject";
message.Body="Message Body";
System.Web.Mail.SmtpMail.SmtpServer="SMTP Server Address";
System.Web.Mail.SmtpMail.Send(message);
I created a class named Emailer, that contains functions like:
SendEmail(string to, string from, string body)
SendEmail(string to, string from, string body, bool isHtml)
And so I can just put this a single line in my code to send an e-mail:
Emailer.SendEmail("name#site.com", "name2#site.com", "My e-mail", false);
I mean, it's not too complex, but I figured there was a standard, accepted solution out there.
Something like this?
using System;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using MailMessage=System.Net.Mail.MailMessage;
class CTEmailSender
{
string MailSmtpHost { get; set; }
int MailSmtpPort { get; set; }
string MailSmtpUsername { get; set; }
string MailSmtpPassword { get; set; }
string MailFrom { get; set; }
public bool SendEmail(string to, string subject, string body)
{
MailMessage mail = new MailMessage(MailFrom, to, subject, body);
var alternameView = AlternateView.CreateAlternateViewFromString(body, new ContentType("text/html"));
mail.AlternateViews.Add(alternameView);
var smtpClient = new SmtpClient(MailSmtpHost, MailSmtpPort);
smtpClient.Credentials = new NetworkCredential(MailSmtpUsername, MailSmtpPassword);
try
{
smtpClient.Send(mail);
}
catch (Exception e)
{
//Log error here
return false;
}
return true;
}
}
Maybe you're looking for SmtpClient?
I use a generic class made out of this old Stack Overflow Answer.
Try this.
public bool SendEmail(MailAddress toAddress, string subject, string body)
{
MailAddress fromAddress = new MailAddress("pull from db or web.config", "pull from db or web.config");
string fromPassword = "pull from db or config and decrypt";
string smtpHost = "pull from db or web.config";
int smtpPort = 587;//gmail port
try
{
var smtp = new SmtpClient
{
Host = smtpHost,
Port = smtpPort,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = body,
IsBodyHtml = true
})
{
smtp.Send(message);
}
return true;
}
catch (Exception err)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(err);
return false;
}
}
This is a snippet from one of my projects. It's a little more feature-packed than some of the other implementations.
Using this function allows you to create an email with:
Tokens that can be replaced with actual values at runtime
Emails that contain both a text and HTML view
public MailMessage createMailMessage(string toAddress, string fromAddress, string subject, string template)
{
// Validate arguments here...
// If your template contains any of the following {tokens}
// they will be replaced with the values you set here.
var replacementDictionary = new ListDictionary
{
// Replace with your own list of values
{ "{first}", "Pull from db or config" },
{ "{last}", "Pull from db or config" }
};
// Create a text view and HTML view (both will be in the same email)
// This snippet assumes you are using ASP.NET (works w/MVC)
// if not, replace HostingEnvironment.MapPath with your own path.
var mailDefinition = new MailDefinition { BodyFileName = HostingEnvironment.MapPath(template + ".txt"), IsBodyHtml = false };
var htmlMailDefinition = new MailDefinition { BodyFileName = HostingEnvironment.MapPath(template + ".htm"), IsBodyHtml = true };
MailMessage htmlMessage = htmlMailDefinition.CreateMailMessage(email, replacementDictionary, new Control());
MailMessage textMessage = mailDefinition.CreateMailMessage(email, replacementDictionary, new Control());
AlternateView plainView = AlternateView.CreateAlternateViewFromString(textMessage.Body, null, "text/plain");
AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlMessage.Body, null, "text/html");
var message = new MailMessage { From = new MailAddress(from) };
message.To.Add(new MailAddress(toAddress));
message.Subject = subject;
message.AlternateViews.Add(plainView);
message.AlternateViews.Add(htmlView);
return message;
}
Assuming you have your Web.config set up for NetMail, you can call this method from a helper method like so:
public bool SendEmail(MailMessage email)
{
var client = new SmtpClient();
try
{
client.Send(message);
}
catch (Exception e)
{
return false;
}
return true;
}
SendMail(createMailMessage("to#email.com", "from#email.com", "Subject", "~/Path/Template"));