Can i send email without giving password on the NetworkCredentials? here is my code.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
MailMessage Myemail = new MailMessage();
private void btnsendemail_Click(object sender, EventArgs e)
{
SmtpClient myGmailserver = new SmtpClient("smtp.gmail.com",587);
myGmailserver.Credentials = new NetworkCredential("Email ID", "password");
Myemail.From = new MailAddress("Email ID");
Myemail.To.Add(tbTo.Text);
Myemail.Subject = tbsubject.Text;
Myemail.Body = tbmsg.Text;
myGmailserver.EnableSsl = true;
myGmailserver.Send(Myemail);
}
}
on the line myGmailserver.Credentials = new NetworkCredential("Email ID", "Password"); it asks for a password for that specific email what if i want to send email to someone and not knowing the password of that email how can i do it? please answer
Ok,I got my answer the password was for the credential not for the recipients..I got another thing to ask,I add the timer in my form and the timer is ticking.For example at "8:00pm" an email should be sent automatically to the manager sales for sale reporting.Someone help me with this please.
Related
Does anyone know how i would code this:
to send an email to the admin/manager everyday at a specific time including a table from the database (Stock Table - which only has four pieces of stock) so they will be informed of their stock levels and if they need to reorder.
Or else
Something in which will send an email to the manager/ admin if one of these four stock levels are low informing them a certin materials/ piece of stock has reached the minimum level and to re order.
I have the code for sending an email:
protected void Button1_Click1(object sender, EventArgs e)
{
MailMessage mail = new MailMessage(from.Text, to.Text, subject.Text, body.Text);
SmtpClient Client = new SmtpClient(smtp.Text);
Client.Port = 587;
Client.Credentials = new System.Net.NetworkCredential(username.Text, password.Text);
Client.EnableSsl = true;
Client.Send(mail);
Response.Write("<script LANGUAGE='JavaScript' >alert('Mail Sent')</script>");
}
any help is welcomed!!!
Thank you!
You need a scheduler so you can schedule a daily task to check the stock levels and send an email if needed. You can achieve this using hangfire if you want to keep everything inside your asp.net application. Hangfire is a scheduler. Check https://www.hangfire.io/
The code would look like this
RecurringJob.AddOrUpdate(
() => {
//TODO: Check your Stock Table DB
var from = "noreply#<yourcompany>.com"
var to = "admin#<yourcompny>.com"
var subject = "Low stock"
var body = "The following items are low in stock : "
// TODO: append items to body variable
MailMessage mail = new MailMessage(from, to, subject, body);
SmtpClient Client = new SmtpClient(smtp.Text);
Client.Port = 587;
Client.Credentials = new System.Net.NetworkCredential(username.Text, password.Text);
Client.EnableSsl = true;
Client.Send(mail);},
Cron.Daily);
});
use Windows Service to Monitoring the data, hour and DB.
private void mainTimer_Tick(object sender, EventArgs e)
{
try
{
if (ConfigsHTM["exechour"] != null)
{
if (DateTime.Now.ToString("HH:mm:ss") == ConfigsHTM["exechour"].ToString())
{
ClassProcessing clsProc = new ClassProcessing();
clsProc.StartDate = DateTime.Now.AddDays(-1);
clsProc.EndDate = DateTime.Now.AddDays(-1);
clsProc.ProcessAll();
if (StatusHTM.Count > 0)
StatusHTM.Clear();
StatusHTM.Add("locationstatus","Todas as Unidades");
StatusHTM.Add("typestatus","Agendado");
StatusHTM.Add("exechourstatus", DateTime.Now.ToString("F"));
if (clsProc.ReprocessingDone)
StatusHTM.Add("statusstatus","OK");
else
StatusHTM.Add("statusstatus", "Falhou");
ClassStatus clsStt = new ClassStatus();
clsStt.StatusHT = StatusHTM;
clsStt.SaveStatus();
GetStatus();
}
}
}
catch (Exception ex)
{
ClassLog clsLog = new ClassLog();
clsLog.EventData = "Falha ao Iniciar a Execução do Aplicativo";
clsLog.ErrorLog();
clsLog.EventData = ex.ToString();
clsLog.ErrorLog();
}
}
I am trying to make a program which sends emails to gmail server. I have completed my goal but now my next goal is to make a login form where I can login with different gmail accounts and send mails.
Here's the code for the Login form:
private void btnLogin_Click(object sender, EventArgs e)
{
User user = new User();
user.Email = textBoxEmail.Text;
user.Password = textBoxPassword.Text;
}
I want my user.Email and user.Password to be saved in the second form (main form), which is this:
private void btnSend_Click(object sender, EventArgs e) {
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
MailMessage mail = new MailMessage();
mail.From = new MailAddress(/*I want user.Email to be here */,"Pavel Valeriu");
mail.To.Add(textBoxTo.Text);
mail.Subject = textBoxSubject.Text;
mail.Body = richText.Text;
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("pavelvaleriu24#gmail.com", /* and user.Password here */);
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail sent");
Close();
}
You can pass the value from the login form to the main form through the constructor
FormLogin:
private void btnLogin_Click(object sender, EventArgs e)
{
User user = new User();
user.Email = textBoxEmail.Text;
user.Password = textBoxPassword.Text;
FormMain frm = new FormMain (textBoxEmail.Text,textBoxPassword.Text);
frm.show();
}
FormMain:
public FormMain(string _email,string _password)
{
InitializeComponent();
Email = _email;
Password = _password;
}
string Email = sting.Empty;
string Password = string.Empty;
private void btnSend_Click(object sender, EventArgs e)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress(Email ,"Pavel Valeriu");
mail.To.Add(textBoxTo.Text);
mail.Subject = textBoxSubject.Text;
mail.Body = richText.Text;
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("pavelvaleriu24#gmail.com", Password );
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
MessageBox.Show("mail Send");
Close();
}
EDIT :-
Include the default constructor for the Form
public FormMain()
{
InitializeComponent();
}
You can define a static class UserInformation with field static string Username & static string Password and in the first form
UserInformation.Username = "Sth";
and in second form
youTextBox.Text = UserInformation.Username.
Please read the http://msdn.microsoft.com/en-us/library/79b3xss3.aspx for more information
You could declare User class as public static on your first from:
public static class User...
...
private void btnLogin_Click(object sender, EventArgs e)
{
User.Email = textBoxEmail.Text;
User.Password = textBoxPassword.Text;
}
and on Main form access the User properties of Form1:
...
mail.From =Form1.User.Email
If security and design is no big issue and you 'just want it to work', you can go ahead and create a static class that can hold this information for you, like a data provider.
public static class LoginDataProvider
{
public static string Email {get; set;}
public static string Password {get; set;}
}
You can then go ahead and get save the information in your login form:
LoginDataProvider.Email = textBoxEmail.Text;
LoginDataProvider.Password = textBoxPassword.Text;
You can then go ahead and retrieve the information in the second form the same way.
If you are developing your appication in ASP.NET you can mention username and password in 'Session' other wise, you are moving with window application you can store credentials in global variables and access it any web forms
When you create the object of main form, when the user is authenticated, create a constructor to pass the user's email & password like
mainForm(string userEmail, string password) or mainForm(User user)
So
User user = new User();
user.Email = textBoxEmail.Text;
user.Password = textBoxPassword.Text;
If(user.Authenticate())
{
//call new MainForm(user)
I have this class that send emails. I log in using my isp email and send it to my gmail email.
Now i want to do that when someone will download/get my application it will check each 1 minute for my gmail account address for a specific email with a specific subject so the email subject will be like a code for example the email subject will be: 16765645
Once the application downloaded the email i want to display the email content in a textBox and also to write on a text file the email content. Also i want that the application will check the email time download after it was downloaded so the application will not download the same email all the time.
This is how i'm sending emails today:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DannyGeneral;
using System.Net.Mail;
using System.Net;
using System.Net.Mime;
using System.IO;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing;
namespace Diagnostic_Tool_Blue_Screen
{
class SendEmail
{
private MailMessage photosmessage;
public bool textfilessendended;
public bool photossendended;
Label lbl1;
Label lbl3;
Button SendLogFile;
MailMessage message;
MailMessage docmessage;
public int timerdelay;
public Timer timer3;
public SendEmail(Label label2, Label label3, Button slf, int timerd, Timer timer)
{
textfilessendended = false;
photossendended = false;
lbl1 = label2;
lbl3 = label3;
SendLogFile = slf;
timerdelay = timerd;
timer3 = timer;
}
public void SendLogger()
{
string log_file_name = "logger.txt";
string logger_file_to_read = Path.GetDirectoryName(Application.LocalUserAppDataPath) + #"\log";
string LoggerFile = Path.Combine(logger_file_to_read, log_file_name);
try
{
MailAddress from = new MailAddress("test#gmail.com", "User " + (char)0xD8 + " Name",
System.Text.Encoding.UTF8);
MailAddress to = new MailAddress("test#test.net");
message = new MailMessage(from, to);
message.Body = "Please check the log file attachment i have some bugs.";
string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });
message.Body += Environment.NewLine + someArrows;
message.BodyEncoding = System.Text.Encoding.UTF8;
message.Subject = "Log File For Checking Bugs" + someArrows;
message.SubjectEncoding = System.Text.Encoding.UTF8;
Attachment myAttachment = new Attachment(LoggerFile, MediaTypeNames.Application.Octet);
message.Attachments.Add(myAttachment);
SmtpClient ss = new SmtpClient("smtp.gmail.com", 587);
ss.SendCompleted += new SendCompletedEventHandler(ss_SendCompleted);
ss.EnableSsl = true;
ss.Timeout = 10000;
ss.DeliveryMethod = SmtpDeliveryMethod.Network;
ss.UseDefaultCredentials = false;
ss.Credentials = new NetworkCredential("meuser", "mepassword");
string userState = "test message1";
ss.SendAsync(message, userState);
lbl3.Enabled = true;
lbl3.Visible = true;
lbl3.BackColor = Color.DarkSeaGreen;
lbl3.Text = "Sending email please wait";
SendLogFile.Enabled = false;
}
catch (Exception errors)
{
Logger.Write("Error sending message :" + errors);
}
}
private void ss_SendCompleted(object sender, AsyncCompletedEventArgs e)
{
timerdelay = 0;
timer3.Start();
String token = (string)e.UserState;
if (e.Cancelled)
{
Logger.Write("[{0}] Send canceled." + token);
SendLogFile.Enabled = true;
}
if (e.Error != null)
{
lbl3.Enabled = true;
lbl3.Visible = true;
lbl3.BackColor = Color.DarkSeaGreen;
lbl3.Text = "There was a problem with sending the log file please try again later and check the log file for more information";
Logger.Write("There was a problem with sending the log file please try again later and check the log file for more information :" + e.Error.ToString());
SendLogFile.Enabled = true;
}
else
{
SendLogFile.Enabled = true;
message.Dispose();
lbl3.Enabled = true;
lbl3.Visible = true;
lbl3.BackColor = Color.DarkSeaGreen;
lbl3.Text = "Email have been sent successfully";
Logger.Write("Attached log file have been emailed successfully");
lbl1.BringToFront();
lbl1.Visible = true;
lbl1.Text = "The log file have been sent on: " + DateTime.Now;
}
}
The idea in general is to use the email like a server to transfer a push messages like updates. So when a user is downloading my program and run if any X minutes there a new email he will see it in the program like a new update.
The idea in general is to use the email like a server to transfer a push messages like updates. So when a user is downloading my program and run if any X minutes there a new email he will see it in the program like a new update.
Honestly, this sounds more like a job for a web service than an email client. You can have your client periodically consume a web service that publishes the latest update message. It will be much simpler for you to implement, and there is a plethora of documentation for doing so.
If you let web services do all the heavy lifting for you, you'll have less code to write, and have to worry less about making a secure, stable solution. Using email to do this seems very kludgy.
Yesterday, i had a task assigned by my senior to build a windows forms application in .net which looked like the image i attached. I did all the stuff regarding the sending process of the email application, but i stuck at one place, i couldn't figure out how to authenticate the password in the email form. The password must be of the same email, which was provided in the "From :" fields.
Here is the code behind of my form,
public partial class Form1 : Form
{
MailMessage message;
SmtpClient smtp;
public Form1()
{
InitializeComponent();
lbl_Error.Visible = false;
}
private void chk_Show_Password_CheckedChanged(object sender, EventArgs e)
{
if (chk_Show_Password.Checked == true)
txt_Password.PasswordChar= '\0';
else
txt_Password.PasswordChar='*';
}
private void btn_Send_Click(object sender, EventArgs e)
{
btn_Send.Enabled = false;
txt_Password.Text = "";
try
{
message = new MailMessage();
if(isValidEmail(txt_From.Text))
{
message.From = new MailAddress(txt_From.Text);
}
if (isValidEmail(txt_To.Text))
{
message.To.Add(txt_To.Text);
}
message.Body = txt_Details.Text;
//attributes for smtp
smtp = new SmtpClient("smtp.gmail.com");
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential("imad.majid90#gmail.com", "mypassword");
smtp.Send(message);
}
catch(Exception ex)
{
btn_Send.Enabled = true;
MessageBox.Show(ex.Message);
}
}
public bool isValidEmail(string email)
{
bool flagFalse = false; ;
if (!email.Contains('#'))
{
lbl_Error.Visible = true;
lbl_Error.ForeColor = System.Drawing.Color.Red;
lbl_Error.Text = "Email address must contain #";
return flagFalse;
}
return true;
}
}
Assuming you're using Gmail like the screenshot you posted shows, you can't check the password without trying to send the email.
My advice would be to attempt to send the email and catch an Exception if it fails. You can then show some indication that there has been an error, like a MessageBox or a Label on your form.
See the documentation for SmtpClient. The Send methods will throw an SmtpException if authentication fails.
EDIT:
Well, after seeing the additional code you posted, you are already handling any exceptions that are thrown, including an authentication failure. The user will see a MessageBox if the password is incorrect.
catch(Exception ex)
{
btn_Send.Enabled = true;
// MessageBox.Show(ex.Message);
lbl_Error.Text = "Invalid Username/Password";
}
Do a try catch for SmtpException and display the information to the user is unauthenticated.
http://msdn.microsoft.com/en-us/library/h1s04he7.aspx
It looks like your using Windows Authentication. It might be easier to fetch the user's email from Active Directory rather then prompting for credentials.
How to obtain email address with window authentication
I'm using the PasswordRecovery Control and can't send more then one email when there are multiple accounts with the same email. I get a MembershipUserCollection with Membership.FindUsersByEmail. I then loop through it in a foreach. My problem is if there is more then one user it only sends the last email. How can I get it to send an email for each account as it loops through? The delagate is called the correct number of times. Also, I know they are all going to the same email, but would like there to be one sent for each account.
Code Snip:
protected void PasswordRecovery1_SendingMail(object sender, MailMessageEventArgs e)
{
}
bool IsValidEmail(string strIn)
{
// Return true if strIn is in valid e-mail format.
return Regex.IsMatch(strIn, #"^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}
protected void PasswordRecovery1_VerifyingUser(object sender, LoginCancelEventArgs e)
{
if (IsValidEmail(PasswordRecovery1.UserName))
{
// string uName = Membership.GetUserNameByEmail(PasswordRecovery1.UserName) ?? PasswordRecovery1.UserName;
MembershipUserCollection users = Membership.FindUsersByEmail(PasswordRecovery1.UserName);
if (users.Count < 1)
{
PasswordRecovery1.UserName = " ";
PasswordRecovery1.UserNameFailureText = "That user is not available"; }
else
{
foreach (MembershipUser user in users)
{
PasswordRecovery1.UserName = user.UserName;
PasswordRecovery1.SendingMail += PasswordRecovery1_SendingMail;
PasswordRecovery1.SuccessTemplateContainer.Visible = true;
}
}
}
else
{
PasswordRecovery1.UserName = " ";
PasswordRecovery1.UserNameFailureText ="Please enter a valid e-mail";
}
}
Figured it out ... the way I was originally doing it would not work, so I went semi-custom. I added an event handler on the submit button and edited the code as shown below. As you can see, I simply looped thorough the collection. Not the best I'm sure, but it works and is easy to understand.
The body of the email is created in a txt file with html formatting. Using the mailDefinition class allows me to have replacement strings, which simplifies the emails body creation.
It sends a separate email for each account to the same email. I could have put them all into a single email, but this is what they wanted ...
protected void PasswordRecovery1_SendingMail(object sender, MailMessageEventArgs e)
{
e.Cancel = true;
}
bool IsValidEmail(string strIn)
{
// Return true if strIn is a valid e-mail
return Regex.IsMatch(strIn, #"^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
}
protected void SubmitLinkButton_Click(object sender, EventArgs e)
{
if (IsValidEmail(PasswordRecovery1.UserName))
{
// Get user collection by shared email
MembershipUserCollection users = Membership.FindUsersByEmail(PasswordRecovery1.UserName);
if (users.Count < 1)
{
PasswordRecovery1.UserName = " ";
PasswordRecovery1.UserNameFailureText = "That user is not available";
}
else
{
// Loop and email each user in collection
foreach (MembershipUser user in users)
{
MembershipUser ur = Membership.GetUser(user.UserName);
DateTime now = DateTime.Now;
// Using MailDefinition instead of MailMessage so we can substitue strings
MailDefinition md = new MailDefinition();
// list of strings in password.txt file to be replace
ListDictionary replacements = new ListDictionary();
replacements.Add("<%UserName%>", ur.UserName);
replacements.Add("<%Password%>", ur.GetPassword());
// Text file that is in html format
md.BodyFileName = "absolute path to password.txt";
md.IsBodyHtml = true;
md.Priority = MailPriority.High;
md.Subject = "Email Subject Line - " + now.ToString("MM/dd - h:mm tt");
md.From = ConfigurationManager.AppSettings["FromEmailAddress"];
// Add MailDefinition to the MailMessage
MailMessage mailMessage = md.CreateMailMessage(ur.Email, replacements, this);
mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["FromEmailAddress"], "Friendly Name");
SmtpClient m = new SmtpClient();
m.Host = "127.0.0.1";
m.Send(mailMessage);
PasswordRecovery1.UserName = user.UserName;
PasswordRecovery1.SendingMail += PasswordRecovery1_SendingMail;
}
}
}
else
{
PasswordRecovery1.UserName = " ";
PasswordRecovery1.UserNameFailureText = "Please enter a valid e-mail";
}
}