How to send value from textBox to mail? - c#

I got this idea of making a mail sender. I tried to look for solutions but none really worked and they were badly explained or if it is even possible to do this?
So i basically have this if else code that check's if it's empty or not and if it's not it would send the value to mail.
using System.Net.Mail; //i think this is what i need?
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrWhiteSpace(textBox1.Text) && string.IsNullOrWhiteSpace(textBox2.Text))
{
MessageBox.Show("You're empty!");
}
else if(Int32.Parse(textBox1.Text) != 0)
{
// send text box to mail
}
else
{
MessageBox.Show("Something went wrong.");
System.Threading.Thread.Sleep(2000);
MessageBox.Show("Closing");
System.Threading.Thread.Sleep(1000);
this.Close();
}
}
Is someone willing to direct me in the correct direction or perhaps help me explain how to do it?

You can put textBox1.Text as an email body, something like this :
mail.From = new MailAddress(emailaddress);
mail.To.Add(recipient);
mail.Subject = "Test Mail";
mail.Body = textBox1.Text; // sets the body to the text box's content
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential(emailaddress, password);
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
System.Windows.Forms.MessageBox.Show("Mail sent");

Try this :
private void button1_Click(object sender, EventArgs e)
{
sendMailToAdmin(textbox1.Text,textbox2.text);
}
protected void sendMailToAdmin(string uname, string email)
{
MailMessage myMsg = new MailMessage();
myMsg.From = new MailAddress("****#mail.com");
myMsg.To.Add(email);
myMsg.Subject = "New User Email ";
myMsg.Body = "New User Information\n\nUser Name: " + uname + "\nEmail : " + email;
// your remote SMTP server IP.
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.Credentials = new System.Net.NetworkCredential("****#mail.com", "pass***");
smtp.EnableSsl = true;
smtp.Send(myMsg);
}

Related

i cant remove a path in my sending email form [winform]

my email format looks like this or my design:
my cross is not working even if i press the cross and send an email it still sends an attached file
still i tried everything Eg i used if else conditions and if you can help me fix this it would mean a lot and thanks in advance for looking at my question
String path = "";
public Form3()
{
InitializeComponent();
}
private void label9_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
//to add attached file
path = openFileDialog1.InitialDirectory + openFileDialog1.FileName;
label10.Text = path;
pictureBox1.ImageLocation = path;
}
}
private void label12_Click(object sender, EventArgs e)
{
//cross to remove the attached file
String path = "";
label10.Text = "'Attached File Location'";
pictureBox1.ImageLocation = path;
}
private void label11_Click(object sender, EventArgs e)
{
try
{
if (path != "")
{
MailMessage message = new MailMessage();
SmtpClient smtp = new SmtpClient();
message.From = new MailAddress(textBox2.Text);
message.To.Add(new MailAddress(textBox3.Text));
message.Subject = textBox1.Text;
message.Body = richTextBox1.Text;
//attached path sendds here
message.Attachments.Add(new Attachment(path));
smtp.Port = 587;
smtp.Host = "smtp." + textBox5.Text.ToLower() + ".com";
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = true;
smtp.Credentials = new NetworkCredential(textBox2.Text, textBox4.Text);
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(message);
MessageBox.Show("Success, Email has been successfully sent to "+textBox3.Text);
}
else if(path == "")
{
MailMessage message = new MailMessage();
SmtpClient smtp = new SmtpClient();
message.From = new MailAddress(textBox2.Text);
message.To.Add(new MailAddress(textBox3.Text));
message.Subject = textBox1.Text;
message.Body = richTextBox1.Text;
smtp.Port = 587;
smtp.Host = "smtp." + textBox5.Text.ToLower() + ".com";
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = true;
smtp.Credentials = new NetworkCredential(textBox2.Text, textBox4.Text);
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(message);
MessageBox.Show("Success, Email has been successfully sent to " +textBox3.Text);
}
You are using a local path variable
private void label12_Click(object sender, EventArgs e)
{
//cross to remove the attached file
String path = "";
use global path instead
private void label12_Click(object sender, EventArgs e)
{
//cross to remove the attached file
path = "";

I have a error on progress bar when sending email

I would like to have a progress bar when sending the auto generated email but I'm getting errors. Please help me fix this. Any type of response is greatly appreciated.
I don't know if I'm on the right path, I'm a beginner on C# and just relying guides online so.
This line has the error
new System.Threading.Thread(new System.Threading.ThreadStart(btnSend_Click));
private void btnSend_Click(object sender, EventArgs e)
{
//Cursor.Current = Cursors.WaitCursor;
try
{
MailMessage loginInfo = new MailMessage();
string em = "angelicasarimo15#gmail.com";
loginInfo.To.Add(em.ToString());
loginInfo.From = new MailAddress("vicserna1997#gmail.com");
loginInfo.Subject = "Requesting Supplies";
loginInfo.Body = "We want another supplies for blah blah blah" + System.Environment.NewLine +
"This is a system generated email.";
loginInfo.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("vicserna1997#gmail.com", "*Pass*");
smtp.Send(loginInfo);
MessageBox.Show("Email has been sent!", "Sent", MessageBoxButtons.OK);
progressBar1.Visible = true;
progressBar1.Style = ProgressBarStyle.Marquee;
System.Threading.Thread thread =
new System.Threading.Thread(new System.Threading.ThreadStart(btnSend_Click));
thread.Start();
}
catch
{
MessageBox.Show("Message not sent please check you internet connection", "Not Sent", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning);
}
}
Use SendAsync and subscribe to SendCompleted. This will notify you the sending process is completed. I don't believe its possible to get the progress of the sending email.

How to create an SMTP mail?

I tried to send mail from my asp.net web application.
I want to send my application password to the user mail id, for that I took the password from datatabase using getdetailss function.
btn4getPwd is the button calling the mailing function.
txtusername.Text is the text box containing sending mail address. All values are receiving correctly, no error occur but it's not working ..!
protected void btn4getPwd_Click(object sender, EventArgs e)
{
if (txtusername.Text.Trim() != "")
{
em.username = txtusername.Text.Trim();
DataTable forget = em.getdetailss(10);
string passwd = (forget.Rows[0]["PassCode"].ToString());
try
{
string Subject = "Your NLS Password";
string Body = passwd;
string ToEmail = txtusername.Text.Trim();
string SMTPUser = "mymail#gmail.com", SMTPPassword = "pswd";
MailMessage mail = new MailMessage();
mail.From = new MailAddress(SMTPUser, "AspnetO");
mail.To.Add(ToEmail);
mail.Body = Body;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.Normal;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 25;
smtp.Credentials = new System.Net.NetworkCredential(SMTPUser, SMTPPassword);
smtp.EnableSsl = true;
smtp.Send(mail);
Response.Write("<script language=javascript>alert('Mail send...!! ')</script>");
}
catch (SmtpException ex)
{
lbl4get.Text = "SmtpException ";
}
catch (Exception ex)
{
lbl4get.Text = "Exception";
}
}
else { Response.Write("<script language=javascript>alert('Invalid USERNAME...!! ')</script>"); }
}
smtp.Port = 25; is default port but for as you are sending over SSL use port 587 or 465 (nonstandard, but sometimes used for legacy reasons). Assume NetworkCredential are correct.

Using SMTP in Visual Studio 2012

I am having problems with sending an email using SMTP, it says "waiting for local host" then eventually times out.
My assumption is that SMTP is disabled on local host, so I had a look at the directions here: http://msdn.microsoft.com/en-us/library/8b83ac7t%28v=vs.100%29.aspx But none of the steps were applicable to my computer (Windows 8, asp.net 4, VS 2012)
Is this enabled by default and the problem is my code?
Here is my code
protected void SendMail()
{
MailMessage email = new MailMessage();
email.To.Add(new MailAddress("removed"));
email.Subject = "Contact Form";
email.From = new MailAddress(emailTextbox.Text);
email.Body = "From: " + nameTextbox.Text + "<br />";
email.Body = "Message: " + commentTextbox.Text + "<br />";
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 465;
smtp.Credentials = new NetworkCredential("removed", "removed");
smtp.EnableSsl = true;
smtp.Send(email);
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
SendMail();
messageLabel.Text = "Thanks for your email, we will get back to you shortly.";
}
catch (Exception error) {
messageLabel.Text = "Error " + error;
}
}
Any help is appreciated, thanks!
Please see, if adding following configuration helps:
smtp.UseDefaultCredentials = false;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

I have a C# application which emails out Excel spreadsheet reports via an Exchange 2007 server using SMTP. These arrive fine for Outlook users, but for Thunderbird and Blackberry users the attachments have been renamed as "Part 1.2".
I found this article which describes the problem, but doesn't seem to give me a workaround. I don't have control of the Exchange server so can't make changes there. Is there anything I can do on the C# end? I have tried using short filenames and HTML encoding for the body but neither made a difference.
My mail sending code is simply this:
public static void SendMail(string recipient, string subject, string body, string attachmentFilename)
{
SmtpClient smtpClient = new SmtpClient();
NetworkCredential basicCredential = new NetworkCredential(MailConst.Username, MailConst.Password);
MailMessage message = new MailMessage();
MailAddress fromAddress = new MailAddress(MailConst.Username);
// setup up the host, increase the timeout to 5 minutes
smtpClient.Host = MailConst.SmtpServer;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
smtpClient.Timeout = (60 * 5 * 1000);
message.From = fromAddress;
message.Subject = subject;
message.IsBodyHtml = false;
message.Body = body;
message.To.Add(recipient);
if (attachmentFilename != null)
message.Attachments.Add(new Attachment(attachmentFilename));
smtpClient.Send(message);
}
Thanks for any help.
Simple code to send email with attachement.
source: http://www.coding-issues.com/2012/11/sending-email-with-attachments-from-c.html
using System.Net;
using System.Net.Mail;
public void email_send()
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("your mail#gmail.com");
mail.To.Add("to_mail#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("c:/textfile.txt");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("your mail#gmail.com", "your password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
Explicitly filling in the ContentDisposition fields did the trick.
if (attachmentFilename != null)
{
Attachment attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);
ContentDisposition disposition = attachment.ContentDisposition;
disposition.CreationDate = File.GetCreationTime(attachmentFilename);
disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
disposition.FileName = Path.GetFileName(attachmentFilename);
disposition.Size = new FileInfo(attachmentFilename).Length;
disposition.DispositionType = DispositionTypeNames.Attachment;
message.Attachments.Add(attachment);
}
BTW, in case of Gmail, you may have some exceptions about ssl secure or even port!
smtpClient.EnableSsl = true;
smtpClient.Port = 587;
Here is a simple mail sending code with attachment
try
{
SmtpClient mailServer = new SmtpClient("smtp.gmail.com", 587);
mailServer.EnableSsl = true;
mailServer.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypassword");
string from = "myemail#gmail.com";
string to = "reciever#gmail.com";
MailMessage msg = new MailMessage(from, to);
msg.Subject = "Enter the subject here";
msg.Body = "The message goes here.";
msg.Attachments.Add(new Attachment("D:\\myfile.txt"));
mailServer.Send(msg);
}
catch (Exception ex)
{
Console.WriteLine("Unable to send email. Error : " + ex);
}
Read more Sending emails with attachment in C#
Completing the solution of Ranadheer, using Server.MapPath to locate the file
System.Net.Mail.Attachment attachment;
attachment = New System.Net.Mail.Attachment(Server.MapPath("~/App_Data/hello.pdf"));
mail.Attachments.Add(attachment);
private void btnSent_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress(txtAcc.Text);
mail.To.Add(txtToAdd.Text);
mail.Subject = txtSub.Text;
mail.Body = txtContent.Text;
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(txtAttachment.Text);
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential(txtAcc.Text, txtPassword.Text);
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail send");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void button1_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
openFileDialog1.ShowDialog();
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(openFileDialog1.FileName);
mail.Attachments.Add(attachment);
txtAttachment.Text =Convert.ToString (openFileDialog1.FileName);
}
I've made a short code to do that and I want to share it with you.
Here the main code:
public void Send(string from, string password, string to, string Message, string subject, string host, int port, string file)
{
MailMessage email = new MailMessage();
email.From = new MailAddress(from);
email.To.Add(to);
email.Subject = subject;
email.Body = Message;
SmtpClient smtp = new SmtpClient(host, port);
smtp.UseDefaultCredentials = false;
NetworkCredential nc = new NetworkCredential(from, password);
smtp.Credentials = nc;
smtp.EnableSsl = true;
email.IsBodyHtml = true;
email.Priority = MailPriority.Normal;
email.BodyEncoding = Encoding.UTF8;
if (file.Length > 0)
{
Attachment attachment;
attachment = new Attachment(file);
email.Attachments.Add(attachment);
}
// smtp.Send(email);
smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallBack);
string userstate = "sending ...";
smtp.SendAsync(email, userstate);
}
private static void SendCompletedCallBack(object sender,AsyncCompletedEventArgs e) {
string result = "";
if (e.Cancelled)
{
MessageBox.Show(string.Format("{0} send canceled.", e.UserState),"Message",MessageBoxButtons.OK,MessageBoxIcon.Information);
}
else if (e.Error != null)
{
MessageBox.Show(string.Format("{0} {1}", e.UserState, e.Error), "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else {
MessageBox.Show("your message is sended", "Message", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
In your button do stuff like this
you can add your jpg or pdf files and more .. this is just an example
using (OpenFileDialog attachement = new OpenFileDialog()
{
Filter = "Exel Client|*.png",
ValidateNames = true
})
{
if (attachement.ShowDialog() == DialogResult.OK)
{
Send("yourmail#gmail.com", "gmail_password",
"tomail#gmail.com", "just smile ", "mail with attachement",
"smtp.gmail.com", 587, attachement.FileName);
}
}
Try this:
private void btnAtt_Click(object sender, EventArgs e) {
openFileDialog1.ShowDialog();
Attachment myFile = new Attachment(openFileDialog1.FileName);
MyMsg.Attachments.Add(myFile);
}
I tried the code provided by Ranadheer Reddy (above) and it worked great. If you’re using a company computer that has a restricted server you may need to change the SMTP port to 25 and leave your username and password blank since they will auto fill by your admin.
Originally, I tried using EASendMail from the nugent package manager, only to realize that it’s a pay for version with 30-day trial. Don’t waist your time with it unless you plan on buying it. I noticed the program ran much faster using EASendMail, but for me, free trumped fast.
Just my 2 cents worth.
Use this method it under your email service it can attach any email body and attachments to Microsoft outlook
using Outlook = Microsoft.Office.Interop.Outlook; // Reference Microsoft.Office.Interop.Outlook from local or nuget if you will user a build agent later
try {
var officeType = Type.GetTypeFromProgID("Outlook.Application");
if(officeType == null) {//outlook is not installed
return new PdfErrorResponse {
ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
};
} else {
// Outlook is installed.
// Continue your work.
Outlook.Application objApp = new Outlook.Application();
Outlook.MailItem mail = null;
mail = (Outlook.MailItem)objApp.CreateItem(Outlook.OlItemType.olMailItem);
//The CreateItem method returns an object which has to be typecast to MailItem
//before using it.
mail.Attachments.Add(attachmentFilePath,Outlook.OlAttachmentType.olEmbeddeditem,1,$"Attachment{ordernumber}");
//The parameters are explained below
mail.To = recipientEmailAddress;
//mail.CC = "con#def.com";//All the mail lists have to be separated by the ';'
//To send email:
//mail.Send();
//To show email window
await Task.Run(() => mail.Display());
}
} catch(System.Exception) {
return new PdfErrorResponse {
ErrorMessage = "System cant start Outlook!, make sure outlook is installed on your computer."
};
}

Categories

Resources