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";
}
}
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'm attempting to learn about generating an email with attachment(s) using C# CodeBehind. I would like the web page to use the FileUpload control or something similar to select the file on the network.
I get a "Could not find a part of the path 'E:\Web Sites\myNet\Ztest\TrailerPics\'."
I'm wondering if I'm on the right path... or if there is a better approach.
Thx for any help ~j
Here is my code:
protected void Button1_Click(object sender, EventArgs e)
{
//Get file names from the fileUpload control
var fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
var fileName2 = Path.GetFileName(FileUpload2.PostedFile.FileName);
var fileName3 = Path.GetFileName(FileUpload3.PostedFile.FileName);
//Code block to send email with keyed data
try
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress("DoNotReply#smiley.com");
mail.To.Add("guy.smiley#sesamestreet.com");
mail.Subject = ("IMG");
mail.IsBodyHtml = true;
var client = new SmtpClient("mailout.smiley.com", 25);
string htmlBody;
htmlBody = string.Format("Email Testing for attaching an image");
mail.Body = htmlBody;
//Create the instance of attachments by using the mapped path concatenated with the file name
Attachment addon = new Attachment(Server.MapPath("~/TrailerPics/" + fileName));
Attachment addon2 = new Attachment(Server.MapPath("~/TrailerPics/" + fileName2));
Attachment addon3 = new Attachment(Server.MapPath("~/TrailerPics/" + fileName3));
//Add the attachments as long as the fileUpload control has a file selected
if (FileUpload1.PostedFile.FileName != "")
{
mail.Attachments.Add(addon);
}
if (FileUpload2.PostedFile.FileName != "")
{
mail.Attachments.Add(addon2);
}
if (FileUpload3.PostedFile.FileName != "")
{
mail.Attachments.Add(addon3);
}
//Send mail
client.Send(mail);
//Notify that email was sent
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Email Sent!')", true);
//Close all connections to the files
if (FileUpload1.PostedFile.FileName != "")
{
addon.Dispose();
}
if (FileUpload2.PostedFile.FileName != "")
{
addon2.Dispose();
}
if (FileUpload3.PostedFile.FileName != "")
{
addon3.Dispose();
}
}
catch(Exception ex)
{
//inform user that the email failed
errorLabel.Text = "Something went wrong with the email : " + ex.Message;
}
}
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.
public void Form1_Load(Object sender, EventArgs e)
{
// Other initialization code
mtxtEmailID.Mask = "..........";
what should be the Mask Type in place of dots
mtxtEmailID.MaskInputRejected += new MaskInputRejectedEventHandler(mtxtEmailID_MaskInputRejected)
}
void mtxtEmailID_MaskInputRejected(object sender, MaskInputRejectedEventArgs e)
{
if(!Regex.IsMatch(txtEmailID.Text, "^[a-zA-Z][\w\.-]*[a-zA-Z0-9]#[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"))
the regex here gives me error, let me know what is the right one for email validation.
{
toolTip1.ToolTipTitle = "Invalid Input";
toolTip1.Show("Enter valid email address", mtxtEMailID);
}
}
You can find info about MaskedTextBox here
If you want to validate an Email Address Regex is not the right choice.There are many corner cases that the regex wont cover...
Use MailAddress
try
{
address = new MailAddress(address).Address;
//email address is valid since the above line has not thrown an exception
}
catch(FormatException)
{
//address is invalid
}
But if you need regex, it should be:
.+#.+
This kind of approach in my project made the email validation simple considering only few factors which are important in email like '#' and '.' . I felt not to make it complex as email address for every one isn't compulsory.
private void txtEmailID_Validating(object sender, System.ComponentModel.CancelEventArgs e)
{
string errorMsg;
if (!ValidEmailAddress(txtEmailID.Text, out errorMsg))
{
// Cancel the event and select the text to be corrected by the user.
e.Cancel = true;
txtEmailID.Select(0, txtEmailID.Text.Length);
// Set the ErrorProvider error with the text to display.
this.errorProvider1.SetError(txtEmailID, errorMsg);
}
}
public bool ValidEmailAddress(string txtEmailID, out string errorMsg)
{
// Confirm that the e-mail address string is not empty.
if (txtEmailID.Length == 0)
{
errorMsg = "e-mail address is required.";
return false;
}
// Confirm that there is an "#" and a "." in the e-mail address, and in the correct order.
if (txtEmailID.IndexOf("#") > -1)
{
if (txtEmailID.IndexOf(".", txtEmailID.IndexOf("#")) > txtEmailID.IndexOf("#"))
{
errorMsg = "";
return true;
}
}
errorMsg = "e-mail address must be valid e-mail address format.\n" +
"For example 'someone#example.com' ";
return false;
}
private void txtEmailID_Validated(object sender, EventArgs e)
{
// If all conditions have been met, clear the ErrorProvider of errors.
errorProvider1.SetError(txtEmailID, "");
}