How to click button and open window to send email in c# - c#

I want to create a button so that user can click and it will open a small new window where they can send email. This window will have "From", "To", "Subject", "Content" fields and all of that will have default text, user can edit them (except for "From" field). See image below:
What I tried:
I created an email form by:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<p>
From:<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</p>
To:<asp:Literal ID="Literal2" runat="server"></asp:Literal>
<p>
Subject:<asp:Literal ID="Literal3" runat="server"></asp:Literal>
</p>
Content:<asp:Literal ID="Literal4" runat="server"></asp:Literal>
</form>
</body>
</html>
Then I try to link this form with my current code:
Current code: I can send email by this code:
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtpclientaddresshere");
mail.From = new MailAddress("defaultFromEmail#domain.com");
mail.To.Add("email1#yahoo.com,email2#yahoo.com");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail";
SmtpServer.Credentials = new System.Net.NetworkCredential("mysmtpserver#something.com", "");
SmtpServer.Send(mail);
Now I don't know is this right to use the form above for email window purpose? And how could I format and link all the fields to my working code?

What I have done is like this:
public void SendEmail(string _from, string _fromDisplayName, string _to, string _toDisplayName, string _subject, string _body, string _password)
{
try
{
SmtpClient _smtp = new SmtpClient();
MailMessage _message = new MailMessage();
_message.From = new MailAddress(_from, _fromDisplayName); // Your email address and your full name
_message.To.Add(new MailAddress(_to, _toDisplayName)); // The recipient email address and the recipient full name // Cannot be edited
_message.Subject = _subject; // The subject of the email
_message.Body = _body; // The body of the email
_smtp.Port = 587; // Google mail port
_smtp.Host = "smtp.gmail.com"; // Google mail address
_smtp.EnableSsl = true;
_smtp.UseDefaultCredentials = false;
_smtp.Credentials = new NetworkCredential(_from, _password); // Login the gmail using your email address and password
_smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
_smtp.Send(_message);
ShowMessageBox("Your message has been successfully sent.", "Success", 2);
}
catch (Exception ex)
{
ShowMessageBox("Message : " + ex.Message + "\n\nEither your e-mail or password incorrect. (Are you using Gmail account?)", "Error", 1);
}
}
And I am using it like this:
SendEmail(textBox2.Text, textBox5.Text, textBox3.Text, "YOUR_FULL_NAME", textBox4.Text, textBox6.Text, "YOUR_EMAIL_PASSWORD");
Here is the image:
(Although I am using WinForms and not Windows Presentation Forms).
May this answer would help you.
Cheers!

Related

Send email with img attachment in asp.net to a user with mac mail [duplicate]

sending mail along with embedded image using asp.net
I have already used following but it can't work
Dim EM As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage(txtFrom.Text, txtTo.Text)
Dim A As System.Net.Mail.Attachment = New System.Net.Mail.Attachment(txtImagePath.Text)
Dim RGen As Random = New Random()
A.ContentId = RGen.Next(100000, 9999999).ToString()
EM.Attachments.Add(A)
EM.Subject = txtSubject.Text
EM.Body = "<body>" + txtBody.Text + "<br><img src='cid:" + A.ContentId +"'></body>"
EM.IsBodyHtml = True
Dim SC As System.Net.Mail.SmtpClient = New System.Net.Mail.SmtpClient(txtSMTPServer.Text)
SC.Send(EM)
If you are using .NET 2 or above you can use the AlternateView and LinkedResource classes like this:
string html = #"<html><body><img src=""cid:YourPictureId""></body></html>";
AlternateView altView = AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html);
LinkedResource yourPictureRes = new LinkedResource("yourPicture.jpg", MediaTypeNames.Image.Jpeg);
yourPictureRes.ContentId = "YourPictureId";
altView.LinkedResources.Add(yourPictureRes);
MailMessage mail = new MailMessage();
mail.AlternateViews.Add(altView);
Hopefully you can deduce the VB equivalent.
After searching and trying must be four or five 'answers' I felt I had to share what I finally found to actually work as so many people seem to not know how to do this or some give elaborate answers that so many others have issues with, plus a few do and only give a snippet answer which then has to be interpreted. As I don't have a blog but I'd like to help others here is some full code to do it all. Big thanks to Alex Peck, as it's his answer expanded on.
inMy.aspx asp.net file
<div>
<asp:LinkButton ID="emailTestLnkBtn" runat="server" OnClick="sendHTMLEmail">testemail</asp:LinkButton>
</div>
inMy.aspx.cs code behind c# file
protected void sendHTMLEmail(object s, EventArgs e)
{
/* adapted from http://stackoverflow.com/questions/1113345/sending-mail-along-with-embedded-image-using-asp-net
and http://stackoverflow.com/questions/886728/generating-html-email-body-in-c-sharp */
string myTestReceivingEmail = "yourEmail#address.com"; // your Email address for testing or the person who you are sending the text to.
string subject = "This is the subject line";
string firstName = "John";
string mobileNo = "07711 111111";
// Create the message.
var from = new MailAddress("emailFrom#address.co.uk", "displayed from Name");
var to = new MailAddress(myTestReceivingEmail, "person emailing to's displayed Name");
var mail = new MailMessage(from, to);
mail.Subject = subject;
// Perform replacements on the HTML file (which you're using as a template).
var reader = new StreamReader(#"c:\Temp\HTMLfile.htm");
string body = reader.ReadToEnd().Replace("%TEMPLATE_TOKEN1%", firstName).Replace("%TEMPLATE_TOKEN2%", mobileNo); // and so on as needed...
// replaced this line with imported reader so can use a templete ....
//string html = body; //"<html><body>Text here <br/>- picture here <br /><br /><img src=""cid:SACP_logo_sml.jpg""></body></html>";
// Create an alternate view and add it to the email. Can implement an if statement to decide which view to add //
AlternateView altView = AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html);
// Logo 1 //
string imageSource = (Server.MapPath("") + "\\logo_sml.jpg");
LinkedResource PictureRes = new LinkedResource(imageSource, MediaTypeNames.Image.Jpeg);
PictureRes.ContentId = "logo_sml.jpg";
altView.LinkedResources.Add(PictureRes);
// Logo 2 //
string imageSource2 = (Server.MapPath("") + "\\booking_btn.jpg");
LinkedResource PictureRes2 = new LinkedResource(imageSource2, MediaTypeNames.Image.Jpeg);
PictureRes2.ContentId = "booking_btn.jpg";
altView.LinkedResources.Add(PictureRes2);
mail.AlternateViews.Add(altView);
// Send the email (using Web.Config file to store email Network link, etc.)
SmtpClient mySmtpClient = new SmtpClient();
mySmtpClient.Send(mail);
}
HTMLfile.htm
<html>
<body>
<img src="cid:logo_sml.jpg">
<br />
Hi %TEMPLATE_TOKEN1% .
<br />
<br/>
Your mobile no is %TEMPLATE_TOKEN2%
<br />
<br />
<img src="cid:booking_btn.jpg">
</body>
</html>
in your Web.Config file, inside your < configuration > block you need the following to allow testing in a TempMail folder on your c:\drive
<system.net>
<mailSettings>
<smtp deliveryMethod="SpecifiedPickupDirectory" from="madeupEmail#address.com">
<specifiedPickupDirectory pickupDirectoryLocation="C:\TempMail"/>
</smtp>
</mailSettings>
</system.net>
the only other things you will need at the top of your aspx.cs code behind file are the Using System includes (if I've missed one out you just right click on the unknown class and choose the 'Resolve' option)
using System.Net.Mail;
using System.Text;
using System.Reflection;
using System.Net.Mime; // need for mail message and text encoding
using System.IO;
Hope this helps someone and big thanks to the above poster for giving the answer needed to get the job done (as well as the other link in my code).
It works but im open to improvements.
cheers.
Thanks to the other answers I managed to get this to work - the only difference is the directory of the image - if the image is the same directory as the application than this can be used Ex:Directory.GetCurrentDirectory() + #"\ClientApp\public\img\blur.jpg
public void SendMail(string receiver, string subject, string content)
{
SmtpClient client = new SmtpClient(emailServiceConfig.SmtpServer);
client.EnableSsl = true; // Important ###
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(emailServiceConfig.Username, emailServiceConfig.Password);
MailMessage mailMessage = new MailMessage();
mailMessage.From = new MailAddress(emailServiceConfig.From);
mailMessage.To.Add(receiver);
//mailMessage.Body = content;
mailMessage.Subject = subject;
//Adding image =============================================
string html = #$"<html><body><img src=""cid:PageScreenshot"">{content}</body></html>";
AlternateView altView = AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html);
LinkedResource screenshotRes = new LinkedResource(Directory.GetCurrentDirectory() + #"\ClientApp\public\img\screeenshot2.jpg", MediaTypeNames.Image.Jpeg);
screenshotRes.ContentId = "PageScreenshot";
altView.LinkedResources.Add(screenshotRes);
mailMessage.AlternateViews.Add(altView);
client.Send(mailMessage);
}

Sending mail in .NET -I am going wrong somewhere

I want to send a dummy email from my server in .NET to my mail .
I am just sending mail without manipulation : Please let me know where I am going wrong . I have written my code as below :
<%# Page Language="C#" AutoEventWireup="true" CodeFile="SendingEmail.aspx.cs" Inherits="experiments_asp_SendingEmail" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<h2>Send e-mail to someone#example.com:</h2>
<asp:Button Text="Submit" OnClick="sendMail" runat="server"/>
</form>
</body>
</html>
my .Net Code is shown as below :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class experiments_asp_SendingEmail : System.Web.UI.Page
{
protected void sendMail(object sender, EventArgs e)
{
Console.Write("came here");
CreateTestMessage2("my college server"); //
}
public static void CreateTestMessage2(string server)
{
string to = "xyz#gmail.com";
string from = "xyz#gmail.com";
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the new SMTP client.";
message.Body = #"Using this new feature, you can send an e-mail message from an application very easily.";
SmtpClient client = new SmtpClient(server);
client.UseDefaultCredentials = true;
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}",
ex.ToString());
}
}
}
Please let me know if any issues in this code , Do i need to add anything extra.
I am not getting any error when i click on submit.
Expectation : to send a dummy mail . Please note I am new to <
I believe that you need to supply more information to the SMTP server to accept your request. Lets take Gmail for example. I have taken your code and enabled it to distribute emails off of the google smtp server:
string to = "xyz#gmail.com";
string from = "xyz#gmail.com";
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the new SMTP client.";
message.Body = #"Using this new feature, you can send an e-mail message from an application very easily.";
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
client.EnableSsl = true;
client.UseDefaultCredentials = true;
NetworkCredential nc = new NetworkCredential("yourEmail#gmail.com", "yourPassword");
client.Credentials = nc;
try
{
client.Send(message);
MessageBox.Show("Your message was sent.");
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}",
ex.ToString());
}
As you can see you need to specify the active port the smtp server is listening on, and allow SSL message transfer. The other key part is providing acceptable credentials the SMTP server can validate a user against for authentication. Maybe your college server has a similar architecture. Do you manage the server, or does someone else?

Mandrill Template is sent correctly once every 28 times

When I run the code below the Mandrill Template is sent correctly once every 28 times. Every other time it will send "Test_email". Does anyone know why this is? Can this be a trial version?
html:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
Table
<table style="text-align: center; border-spacing:5px; margin-left: auto;margin-right: auto;vertical-align: middle;width: 600px;background-color:lightgrey; padding-top:15px; padding-bottom:15px; padding-left:10px;padding-right:10px;border-radius:15px;">
<tr>
<td>Some Text here</td>
</tr>
</table>
</body>
</html>
C#
namespace Messages
{
class Program
{
static void Main(string[] args)
{
var fromAddress = new MailAddress("me#mail.com", "b");
var toAddress = new MailAddress("ano#gmail.com", "To Name");
const string fromPassword = "API Key";
const string subject = "test template email";
//const string body = "Test-email";
TemplateContent tp = new TemplateContent();
tp.name = "Test_email";
var smtp = new SmtpClient
{
Host = "smtp.mandrillapp.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
Subject = subject,
Body = tp.name
})
{
smtp.Send(message);
}
}
}
}
If they're showing in the Outbound Activity, then your code was fine and Mandrill processed the mail. Is the issue that it shows as delivered in Mandrill but you don't see it? Or that it doesn't look like the template was applied? If you're sending to Gmail, you might see the content hidden because of the emails being included in a conversation. Look for three dots to expand the information. If they all have the same subject line and content, then Gmail will hide previously-received content as part of the conversations feature. If that's not the issue, then you should clarify exactly where you're seeing an issue in the process.

send email as template in asp.net

i am able to send and receive emails through my application, but its jus plain text content. I want to send full formatted content decorated with css and div or tables.
How to do it?
I am using asp.net 3.5 VS2010.
public void Send(string To, string Subject, string Body)
{
System.Net.Mail.MailMessage m = new System.Net.Mail.MailMessage("mymail#gmail.com", To);
m.Subject = Subject;
m.Body = Body;
m.IsBodyHtml = true;
m.From = new MailAddress("mymail#gmail.com");
m.To.Add(new MailAddress(To));
SmtpClient smtp = new SmtpClient();
smtp.Host = "198.208.0.***";
NetworkCredential authinfo = new NetworkCredential("mymail#gmail.com", "password");
smtp.UseDefaultCredentials = false;
smtp.Credentials = authinfo;
smtp.Send(m);
}
calling this function like
Send("mynewmail#gmail.com", "testmail", "new test body");
this is my function.
The answer is here : http://social.msdn.microsoft.com/Forums/en/netfxnetcom/thread/c65502fa-955e-4fa1-b409-238bbb677df7
I think the main thing you're missing is the MIME Content Type on the LinkedResource.
myMagic.css:
body {
background-color: rgb(240,240,240);
font-family: Verdana,Arial,Helvetica,Sans-serif;
font-size: 10pt;
}
h2 {
background-color: rgb(255,255,128);
color: rgb(255,0,0);
}
p {
background-color: rgb(0,0,255);
color: rgb(0,255,0);
font-style: italic;
}
Program.cs:
using System.Net.Mail;
using System.Net.Mime;
namespace MailMessageHTML
{
class Program
{
private static MailMessage ConstructMessage(string from, string to, string subject)
{
const string textPlainContent =#"You need a HTML-capable mail agent to read this message.";
const string textHtmlContent =#"<html><head><link rel='stylesheet' type='text/css' href='cid:myMagicStyle' />
</head>
<body>
<h2>Hello world!</h2>
<p>This is a test HTML e-mail message.</p>
</body>
</html>
";
MailMessage result = new MailMessage(from, to, subject, textPlainContent);
LinkedResource cssResource = new LinkedResource("myMagic.css", "text/css");
//NOTE: Message encoding adds the surrounding <> on this Id cssResource.ContentId =myMagicStyle";
cssResource.TransferEncoding = TransferEncoding.SevenBit;
AlternateView htmlBody = AlternateView.CreateAlternateViewFromString( textHtmlContent , new ContentType("text/html"));
htmlBody.TransferEncoding = TransferEncoding.SevenBit;
htmlBody.LinkedResources.Add(cssResource);
result.AlternateViews.Add(htmlBody);
return result;
}
static void Main(string[] args)
{
MailMessage foo = ConstructMessage(
"sender#foo.com"
,"recipient#bar.com"
, "Test HTML message with style."
);
SmtpClient sender = new SmtpClient();
sender.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
sender.PickupDirectoryLocation = #"...\MailMessageHTML\bin\Debug\";
sender.Send(foo);
}
}
}
NOTE 1: I've specified TransferEncoding.SevenBit on the message parts above. You wouldn't normally do this in a production environment - I've only done it here so you can read the resultant .eml file with Notepad to see what was generated.
NOTE 2: A lot of mail agents won't honour stylesheets linked in message parts. A more-reliable way might be to use inline styles (i.e.: inline ... blocks within the HTML message body).
Good luck,
This answer got from : http://social.msdn.microsoft.com/Forums/en/netfxnetcom/thread/c65502fa-955e-4fa1-b409-238bbb677df7
If you don't need dynamic content (if/else or foreach) or model binding. I think put your template into a text file and use string.Format() is sufficient.
Otherwise, you'll need a template engine. This question may be a good reference for you.
Have a look at MvcMailer on github
It uses a viewengine to render emails so you have all the benefits of viewmodels and templating.
Have a look at http://www.campaignmonitor.com/css/ which shows how to apply CSS to emails.
Also, use inline CSS.. And are you setting emailMessage.IsBodyHtml = true; ?

Need to show MODALPOPUP Extender while clickig on Link button

Need to show MODALPOPUP Extender while clickig on Link button and in modal pop up extender we need to get send an email to the required mail ID holder.
Is there any specifications and functionality to use in ASP.NET with C#.Please suggest me the best.
Thanks in advance
First of all add below mentioned namespace in code behind of aspx page from which you want to send the mail.
using System.Net.Mail;
protected void Button1_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
mail.To.Add("Email ID where email is to be send");
mail.To.Add("Another Email ID where you wanna send same email");
mail.From = new MailAddress("YourGmailID#gmail.com");
mail.Subject = "Email using Gmail";
string Body = "Hi, this mail is to test sending mail"+
"using Gmail in ASP.NET";
mail.Body = Body;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential
("YourUserName#gmail.com","YourGmailPassword");
//Or your Smtp Email ID and Password
smtp.EnableSsl = true;
smtp.Send(mail);
}
For sending mail try the above code in C#
opening the Modalpopup extender on button click
<div id="hiddenDiv" style="display:none; visibility:hidden;">
<asp:Button runat="server" ID="hiddenButton" />
/div>
<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtenderID" runat="server"
BehaviorID="ModalPopupBehaviorID"
TargetControlID="hiddenButton"
PopupControlID="ModalContainer"
/>
...
//Javascript
var modalPopupBehaviorCtrl = $find('ModalPopupBehaviorID');
modalPopupBehaviorCtrl.show();

Categories

Resources