Adding table using mailto and windows forms - c#

I want to open mail to and inside the body of my email I want to create a table and insert values inside my model. So I execute outlook like this:
var mail = $"mailto:test#test.com?subject=ProjectListTest&body={finalString}";
My question is, how can I create a table and add to body of mailto?
Table headers: Name, Customer
so inside each row I want to use something like:
var finalString = string.Empty;
foreach(var customer in CustomerList)
{
finalString = finalString + customer.Name + customer.CustomerKey
}
Is it possible to achieve this? what is the correct format to create a table in Outlook. Regards

pIf the table would be created using the html mail body format, then you can use the following method to generate it:
public string GenerateMailBodyWithTable(List<Customer> customers)
{
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append($"<html>{ Environment.NewLine }<body>{ Environment.NewLine }");
if (customers.Count > 0)
{
stringBuilder.Append($"<table><tr><th>Name</th><th>Key</th></tr>{ Environment.NewLine }");
foreach (Customer customer in customers)
{
stringBuilder.Append($"<tr><th>{ customer._name }</th><th>{ customer._key }</th></tr>{ Environment.NewLine }");
}
stringBuilder.Append($"<table>{ Environment.NewLine }");
}
else
{
stringBuilder.Append($"<p>No customers<p>{ Environment.NewLine }");
}
stringBuilder.Append($"</html>{ Environment.NewLine }</body>");
return stringBuilder.ToString();
}
After generating the html body you can perform the following action to fill the mailbody:
Outlook.Application outlookApp = new Outlook.Application();
Outlook.MailItem mailMessage = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
mailMessage.HTMLBody = GenerateMailBodyWithTable(customers);
mailMessage.Display(true);
Don't forget to place this using statement:
using Outlook = Microsoft.Office.Interop.Outlook;

First at all, you have to create your custom HTML:
string finalString = "<table><tr><td><b>Name</b></td><td><b>Customer</b></td></tr>";
foreach(var customer in CustomerList)
{
finalString += "<tr><td>" + customer.Name + "</td><td>" + customer.CustomerKey + "</td></tr>";
}
finalString += "</table>";
If you are using WinForms and you want to send an email with this body, you can use MailMessage Class from System.Net.Mail and sending it with SmtpClient. This way:
MailMessage mail = new MailMessage("from", "mailto", "Subject", finalString);
mail.IsBodyHtml = true; //Important
SmtpClient smtp = new SmtpClient("serverSMTP");
smtp.EnableSsl = USE_SSL;
smtp.Port = YOUR_PORT;
smtp.Credentials = new System.Net.NetworkCredential("email", "password");
smtp.Send(correo);
If you want to simulate a "mailto" action, you can use:
string command = $"mailto:test#test.com?subject=ProjectListTest&body={finalString}";
Process.Start(command);
Regards

Related

Change text to Bold in Outlook Message Body

please help me with following.
I'm working on creating and modifying outlook messages from template. I need to change some text to Bold.
foreach (XmlNode node in nodeList)
{
string CustomerName = node.SelectSingleNode("CustomerName").InnerText;
string ReportName = node.SelectSingleNode("ReportName").InnerText + ".pdf";
Outlook.Application mailApplication = new Outlook.Application();
Outlook.MailItem mail = mailApplication.CreateItemFromTemplate(#"d:\Friday Report\#TEMPLATES\template.oft") as Outlook.MailItem;
mail.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
mail.Attachments.Add(#"d:\Friday Report\" + ReportName);
mail.Subject = "Application Packaging – Weekly Summary";
CustomerName = "<b>" + CustomerName + "</b> ";
string body = mail.Body;
string new_body = body.Replace("CustomerName", CustomerName );
mail.Body = new_body;
mail.Display(true);
mail.Close(Outlook.OlInspectorClose.olDiscard);
}
If you want to use HTML in your email, you need to set the HTMLBody property instead of Body:
foreach (XmlNode node in nodeList)
{
string CustomerName = node.SelectSingleNode("CustomerName").InnerText;
string ReportName = node.SelectSingleNode("ReportName").InnerText + ".pdf";
Outlook.Application mailApplication = new Outlook.Application();
Outlook.MailItem mail = mailApplication.CreateItemFromTemplate(#"d:\Friday Report\#TEMPLATES\template.oft") as Outlook.MailItem;
mail.BodyFormat = Outlook.OlBodyFormat.olFormatHTML;
mail.Attachments.Add(#"d:\Friday Report\" + ReportName);
mail.Subject = "Application Packaging – Weekly Summary";
CustomerName = "<b>" + CustomerName + "</b> ";
string body = mail.Body;
string new_body = body.Replace("CustomerName", CustomerName );
mail.HTMLBody = new_body;
mail.Display(true);
mail.Close(Outlook.OlInspectorClose.olDiscard);
}
You should use valid HTML, though, by surrounding your mail with <html><body>{your message}</body></html>
This seems to work (see screen shot below the code)
using Microsoft.Office.Interop.Outlook;
using outlookApp = Microsoft.Office.Interop.Outlook;
namespace z_Console_Scratch
{
class Program
{
static void Main(string[] args)
{
Microsoft.Office.Interop.Outlook.Application outlookApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem mailItem = (Microsoft.Office.Interop.Outlook.MailItem)outlookApp.CreateItem(OlItemType.olMailItem);
mailItem.Subject = "test subject";
mailItem.HTMLBody = "<html><body>This is the <strong>funky</strong> message body</body></html>";
mailItem.Display(false);
}
}
}
Note: This works as well: mailItem.HTMLBody = "<html><body>This is the <b>funky</b> message body</body></html>";
Screen Shot

Pass some arguments with link and detect it while loading link page using c#

Process :
Send Email to particular user and mail body contains unique link.
At the same time I need to store that unique link in database across that user.
As User clicks the link from his mail body I need to open one web page and at the loading time I need to validate that link whether it is the same link for that user.
If Yes, load page with reset password form, otherwise show some message of invalidation.
In the above process I just want a code for sending user_id and unique code with link and detect it at the time of loading link page in ASP.net c#.
I used GUID for creating unique link and sends the mail successfully. While loading link page I am unable to validate user.
Here Is my code :
protected void btnRECOVER_PASSWORD_Click(object sender, EventArgs e)
{
SendMail();
}
public void SendMail()
{
login = new NetworkCredential("leaves#nworks.co", "password");
client = new SmtpClient("smtp.1and1.com");
client.Port = Convert.ToInt32(25);
client.EnableSsl = true;
client.Credentials = login;
msg = new MailMessage { From = new MailAddress("leaves#nworks.co", "nWorks Employee", Encoding.UTF8) };
msg.To.Add(new MailAddress("dipak.akhade#nworks.co"));
msg.Subject = "Recover Password For Your nWorks Leave Management Account";
msg.CC.Add(new MailAddress("dipak.a.akhade9192#gmail.com"));
// msg.CC.Add(new MailAddress("*************user mail id*************"));
string strBody = string.Empty;
Guid code = Guid.NewGuid();
strBody += "<html><head></head><body><p>Click the following link to recover your password.</p>";
strBody += Environment.NewLine;
strBody += "<form action='' method='POST' name='myForm1'><a href='http://localhost:19343/LoginForm.aspx'>'" + code.ToString() + "'</form><br>";
strBody += "<br/>Thanks.</body></html>";
msg.Body = strBody;
msg.BodyEncoding = Encoding.UTF8;
msg.IsBodyHtml = true;
msg.Priority = MailPriority.Normal;
msg.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
string userstate = "sending.......";
client.SendAsync(msg, userstate);
string q1 = "insert into RecoverPwdStatus values(101,'" + code.ToString() + "');";
MySqlCommand cmd1 = new MySqlCommand(q1, conn); conn.Open();
MySqlDataReader rdr1 = cmd1.ExecuteReader(); conn.Close();
}
Use following for creation of link :
<a href='http://localhost:19343/ResetPasswordForm.aspx?guid="+code.ToString()+"&userid="+getUser()+"'>
Access these parameter while loading link page and do whatever with them you want...
string v = Request.QueryString["guid"];
string v1 = Request.QueryString["userid"];

Send Email from an Asp.Net Webform Application using Microsoft Outlook

I have anasp.net web form which on click of a button sends i want an email to be sent to my Microsoft outlook email account. I have done this on other
websites but that was using hotmail but all external web email providers are blocked by the companies firewall (as i tried setting up a gmail account) so
i need to use Outlook but i have not idea on how to implent this and solutions i have seen on Google dont seem to work. I dont know if it'll make a
difference or not but i have been informed that the users password epxires every 30days so i suspect i'll need to use windows authenication or something
but not sure.
I'm not sure on how Outlook send the email as i know from past experience from using hotmail that the email is just sent on click of the button but i'm
not sure if outlook would open the email window for the user to click the send button. If it does, i need the information captured on the webform to be
containd in the email and the content of the email body not to be altered (if this can be done, again not ot sure if it can but not a problem if it
can't).
Below is the code i used for when i tried gmail but as i said i was told it wouldnt be allowed.
using System.Configuration;
using System.Net.Mail;
using System.Net;
using System.IO;
protected void BtnSuggestPlace_Click(object sender, EventArgs e)
{
#region Email
try
{
//Creates the email object to be sent
MailMessage msg = new MailMessage();
//Adds your email address to the recipients
msg.To.Add("MyEmailAddress#Test.co.uk");
//Configures the address you are sending the email from
MailAddress address = new MailAddress("EmailAddress#Test.com");
msg.From = address;
//Allows HTML to be used when setting up the email body
msg.IsBodyHtml = true;
//Email subjects title
msg.Subject = "Place Suggestion";
msg.Body = "<b>" + lblPlace.Text + "</b>" + " " + fldPlace.Text
+ Environment.NewLine.ToString() +
"<b>" + lblLocation.Text + "</b>" + " " + fldLocation.Text
+ Environment.NewLine.ToString() +
"<b>" + lblName.Text + "</b>" + " " + fldName.Text;
//Configures the SmtpClient to send the mail
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.EnableSsl = true; //only enable this if the provider requires it
//Setup credentials to login to the sender email address ("UserName", "Password")
NetworkCredential credentials = new NetworkCredential("MyEmailAddress#Test.co.uk", "MyPassword");
client.Credentials = credentials;
//Send the email
client.Send(msg);
}
catch
{
//Lets the user know if the email has failed
lblNotSent.Text = "<div class=\"row\">" + "<div class=\"col-sm-12\">" + "There was a problem sending your suggestion. Please try again."
+ "</div>" + "</div>" + "<div class=\"form-group\">" + "<div class=\"col-sm-12\">" + "If the error persists, please contact Antony." + "</div>" +
"</div>";
}
#endregion
}
edit 2: Now we have established your going through exchance this is how my code has always worked
SmtpClient sptmClient = new SmtpClient("exchange server name")
MailMessage m = new MailMessage();
m.To.Add(new MailAddress("Address"));
m.From = new MailAddress("");
m.Subject = "";
m.Body = "";
m.IsBodyHtml = true;
sptmClient.Send(m);
but there is another answer on here that uses outlook interoperlation that might work better for you
With Exchange it must work.
test this :
using Outlook = Microsoft.Office.Interop.Outlook;
private void SendWithExchange()
{
Outlook.Application oApp = new Outlook.Application();
Outlook.MailItem mail = oApp.CreateItem(
Outlook.OlItemType.olMailItem) as Outlook.MailItem;
mail.Subject = "Exemple à tester";
Outlook.AddressEntry currentUser =
oApp.Session.CurrentUser.AddressEntry;
if (currentUser.Type == "EX")
{
Outlook.ExchangeUser manager =
currentUser.GetExchangeUser();
mail.Recipients.Add(manager.PrimarySmtpAddress);
mail.Recipients.ResolveAll();
//mail.Attachments.Add(#"c:\sales reports\fy06q4.xlsx",
// Outlook.OlAttachmentType.olByValue, Type.Missing,
// Type.Missing);
mail.Send();
}
}

Getting exact File Path with File Upload to send file via Email C# ASP.NET

I want to send a file via email using c# ASP.net (Maybe more files too, but for the moment I'm concerned about sending at least only one file)
For the moment, I do have a method that does work if you want to send an Email
public string EnviarMensaje(int intIdVendedor, string strCorreoPara, string strCorreosAdicionales, string strTema, string strMensaje, string strRuta)
{
string strResultado="";
DataTable dt = ConexionBD.GetInstanciaConexionBD().GetVendedorEspecifico(intIdVendedor);
string strCuerpo = strMensaje + "\n\n\n\nMensaje Enviado Por:\n" + dt.Rows[0]["Vendedor"] + "\n" + dt.Rows[0]["Email"] + "\n" + dt.Rows[0]["Telefono"];
string[] strListaCorreos = strCorreosAdicionales.Split(new Char[] {' ', ','}, StringSplitOptions.RemoveEmptyEntries);
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtpout.secureserver.net");
mail.Subject = strTema;
mail.Body = strCuerpo;
mail.From = new MailAddress(strCorreoDe);
mail.To.Add(strCorreoPara);
foreach (string c in strListaCorreos)
{
mail.To.Add(c);
}
if (strRuta != "")
{
Attachment attachment;
attachment = new Attachment(strRuta);
mail.Attachments.Add(attachment);
}
SmtpServer.Port = 80;
SmtpServer.Credentials = new System.Net.NetworkCredential(strCorreoDe, strContrasena);
SmtpServer.EnableSsl = false;
SmtpServer.Send(mail);
strResultado = "Exito";
}
catch (Exception ex)
{
strResultado = ex.ToString();
}
return strResultado;
}
in aspx I have
<asp:FileUpload ID="fileUploadArchivos" runat="server" />
<asp:ImageButton ID="imgBtnEnviar" runat="server" Height="60px" Width="60px" ImageUrl="~/img/iconos/email.png" CausesValidation = "True" ValidationGroup="vgpCorreo" onclick="imgBtnEnviar_Click" />
and on the cs I have
EnviarEmail objEmail = new EnviarEmail();
protected void imgBtnEnviar_Click(object sender, ImageClickEventArgs e)
{
if (fileUploadArchivos.HasFile)
{
strArchivo = Path.GetTempFileName();\\RIGHT NOW I LEFT IT THIS WAY, BUT I NOW THAT HERE IS THE PROBLEM, I DON'T KNOW WHTAT CAN I DO HERE
}
string strResultado = objEmail.EnviarMensaje((int)Session["IdVendedor"], lblCorreoPara.Text, tbxCorreoPara.Text, tbxTema.Text, tbxMensaje.Text, strArchivo);
}
However, the problem is in a FileUpload.
I have tried many methods like, Server.MapPath, Path.GetFileName, GetDirectoryName, GetFullPath, GetPathRoot... and I'm always getting either nothing, only the filename or a completely different path (I guess is a server kind of path)..
I only for the moment want to get a file path as simple as C:\Test.txt for example...
I suppose that if I can get that exact string from the FileUpload, I'll be able to send it... However, I can't figure out how to make it work.
Hope you can help me
Thanks
If you need a local copy of the file uploaded kept on the server you can just do
fuFileUpload.SaveAs(MapPath(filepath));
Then your strRuta can use the file you just saved via
strRuta = Server.MapPath(filepath);
ready to pass into the new Attachment object.
You don't need to save the file at all to disk, not if all you want to do with it is add it as an attachment.
FileUpload has a FileContent property that is a Stream - some of the constructors of the Attachment class take a stream as a parameter.
The solution is to pass this stream to your method and use it directly.
In code behind:
string strResultado = objEmail.EnviarMensaje((int)Session["IdVendedor"],
lblCorreoPara.Text,
tbxCorreoPara.Text,
tbxTema.Text,
tbxMensaje.Text,
fileUploadArchivos.FileContent);
In your class:
public string EnviarMensaje(int intIdVendedor,
string strCorreoPara,
string strCorreosAdicionales,
string strTema,
string strMensaje,
Stream attachmentData)
{
...
var attachment = new Attachment(attachmentData, "nameOfAttachment");
...
}
You can try with this, using a stream instead of a simple text:
public string EnviarMensaje(int intIdVendedor, string strCorreoPara, string strCorreosAdicionales, string strTema, string strMensaje, string strRuta)
{
string strResultado="";
DataTable dt = ConexionBD.GetInstanciaConexionBD().GetVendedorEspecifico(intIdVendedor);
string strCuerpo = strMensaje + "\n\n\n\nMensaje Enviado Por:\n" + dt.Rows[0]["Vendedor"] + "\n" + dt.Rows[0]["Email"] + "\n" + dt.Rows[0]["Telefono"];
string[] strListaCorreos = strCorreosAdicionales.Split(new Char[] {' ', ','}, StringSplitOptions.RemoveEmptyEntries);
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtpout.secureserver.net");
mail.Subject = strTema;
mail.Body = strCuerpo;
mail.From = new MailAddress(strCorreoDe);
mail.To.Add(strCorreoPara);
foreach (string c in strListaCorreos)
{
mail.To.Add(c);
}
bool hasAttachment = !string.IsNullOrWhitespace(strRuta);
System.IO.FileStream stream = null;
Attachment attachment = null;
if (hasAttachment)
{
// Create a file stream.
stream = new FileStream(strRuta, FileMode.Open, FileAccess.Read);
// Define content type.
ContentType contentType = new ContentType();
contentType.MediaType = MediaTypeNames.Text.Plain; // or whatever your attachment is
// Create the attachment and add it.
attachment = new Attachment(stream, contentType);
mail.Attachments.Add(attachment);
}
SmtpServer.Port = 80;
SmtpServer.Credentials = new System.Net.NetworkCredential(strCorreoDe, strContrasena);
SmtpServer.EnableSsl = false;
SmtpServer.Send(mail);
strResultado = "Exito";
// Don't forget to release the resources if the attachment has been added
if (hasAttachment)
{
data.Dispose();
stream.Close();
stream.Dispose();
}
}
catch (Exception ex)
{
strResultado = ex.ToString();
}
return strResultado;
}

Microsoft Outlook adding cc to email

I currently have existing code that automates and email and sends files. I now need to add a cc. I have looked all over, but can't seem to find out with my existing code. Any help would be greatly appreciated. Thank you.
private void button13_Click(object sender, EventArgs e)
{
//Send Routing and Drawing to Dan
// Create the Outlook application by using inline initialization.
Outlook.Application oApp = new Outlook.Application();
//Create the new message by using the simplest approach.
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
//Add a recipient
Outlook.Recipient oRecip = (Outlook.Recipient)oMsg.Recipients.Add("email#email.com");
oRecip.Resolve();
//Set the basic properties.
oMsg.Subject = "Job # " + textBox9.Text + " Release (" + textBox1.Text + ")";
oMsg.HTMLBody = "<html><body>";
oMsg.HTMLBody += "Job # " + textBox9.Text + " is ready for release attached is the Print and Routing (" + textBox1.Text + ")";
oMsg.HTMLBody += "<p><a href='C:\\Users\\RussellS\\Desktop\\Russell Eng Reference\\" + textBox1.Text + ".PDF'>" + textBox1.Text + " Drawing";
oMsg.HTMLBody += "<p><a href='C:\\Users\\RussellS\\Desktop\\" + textBox1.Text + ".PDF'>" + textBox1.Text + " Routing" + "</a></p></body></html>";
//Send the message
oMsg.Send();
//Explicitly release objects.
oRecip = null;
oMsg = null;
oApp = null;
MessageBox.Show(textBox1.Text + " Print and Routing Sent");
}
According to MSDN there's a CC property on the MailItem class.
string CC { get; set; }
Which can be used to set the names of the CC recipients.
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook._mailitem.cc.aspx
To modify the recipients you can add them to the Recipients collection:
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.recipients.aspx
Which you would use like:
oMsg.Recipients.Add("foo#bar.com");
Please follow this code for adding CC and BCC:
private void SetRecipientTypeForMail()
{
Outlook.MailItem mail = Application.CreateItem(
Outlook.OlItemType.olMailItem) as Outlook.MailItem;
mail.Subject = "Sample Message";
Outlook.Recipient recipTo =
mail.Recipients.Add("someone#example.com");
recipTo.Type = (int)Outlook.OlMailRecipientType.olTo;
Outlook.Recipient recipCc =
mail.Recipients.Add("someonecc#example.com");
recipCc.Type = (int)Outlook.OlMailRecipientType.olCC;
Outlook.Recipient recipBcc =
mail.Recipients.Add("someonebcc#example.com");
recipBcc.Type = (int)Outlook.OlMailRecipientType.olBCC;
mail.Recipients.ResolveAll();
mail.Display(false);
}

Categories