i have a simple contact page on my private homepage.
Offline it works perfectly, online nothing happens.
Any idea?
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
btnSend.Attributes.Add("onmouseover", "changeIMG('" + btnSend.ClientID + "', 'Images/Senden_Hover.jpg');");
btnSend.Attributes.Add("onmouseout", "changeIMG('" + btnSend.ClientID + "', 'Images/Senden.jpg')");
}
}
protected void btnSend_Click(object sender, ImageClickEventArgs e)
{
if (!String.IsNullOrEmpty(txtNachricht.Text))
{
SendEmailUserContact(txtAbsender.Text, txtNachricht.Text);
Response.Redirect("~/Contact_suc.aspx", false);
}
}
public static void SendEmailUserContact(string betreff, string nachricht)
{
SendEmail(betreff, nachricht, "von#exampl.com", "an#example.com");
}
private static void SendEmail(string betreff, string nachricht, string von, string an)
{
///Zambuu
string strSmtpServer = "smtp.example.com";
string strUser = "kontakt#example.com";
string strPasswort = "xxx";
MailMessage mail = new MailMessage();
MailAddress from = new MailAddress(von);
mail.To.Add(an);
mail.From = from;
mail.Subject = betreff;
mail.Body = nachricht;
string host = strSmtpServer;
int port = 25;
SmtpClient client = new SmtpClient(host, port);
NetworkCredential nc = new NetworkCredential(strUser, strPasswort);
client.Credentials = nc;
client.Send(mail);
}
I believe the SMTP have approve the sender. So the machine that hosts the online contact page, is a different machine than the one you are developing on. You have to give access on the mailserver on the machine that hosts the page.
Related
My code works within a local network and I know it will not work outside of the local network as I am using Dns.GetHostEntry to resolve the IP address to hostname and thats fine...
But my if statement is not working, I am getting error "No Host Found" message when trying to resolve hostname from different subnet.
I thought my if statement would stop this error but its not working, can someone help please or tell me how to fix it, code below...
public partial class _Default : System.Web.UI.Page
{
//public string IPaddr1 { get; private set; }
string serviceDesk = "eg#mail.co.uk";
string emailSubject = "MyPc";
string IPaddr = "";
string deviceName = "";
protected void Page_Load(object sender, EventArgs e)
{
getIP();
}
protected void getIP()
{
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDER_FOR"] != null)
{
IPaddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDER_FOR"].ToString();
}
if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
IPaddr = HttpContext.Current.Request.UserHostAddress;
deviceName = Dns.GetHostEntry(IPAddress.Parse(IPaddr)).HostName;
}
if (HttpContext.Current.Request.UserHostAddress.Length != 0)
{
deviceName = "Device name could be found";
}
Label1.Text = "IP Address: " + " " + IPaddr;
Label2.Text = "PC Name: " + " " + deviceName;
}
private void EmailVerificationRequest(string recepientEmail, string subject)
{
try
{
using (MailMessage mailMessage = new MailMessage())
{
StringBuilder sbEmailBody = new StringBuilder();
sbEmailBody.Append("IP address " + IPaddr + "<br/>");
sbEmailBody.Append("Hostname " + " " + deviceName);
mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["FromEmail"]);
mailMessage.Subject = subject;
mailMessage.Body = sbEmailBody.ToString();
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MailAddress(recepientEmail));
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["Host"];
smtp.Port = Convert.ToInt32(ConfigurationManager.AppSettings["Port"]);
smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
if (string.IsNullOrWhiteSpace(NetworkCred.UserName))
{
smtp.UseDefaultCredentials = true;
}
else
{
smtp.Credentials = NetworkCred;
smtp.UseDefaultCredentials = false;
}
smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
try
{
smtp.Send(mailMessage);
}
catch (SmtpException e)
{
}
}
}
catch
{
}
}
protected void Button1_Click(object sender, EventArgs e)
{
EmailVerificationRequest(serviceDesk, emailSubject);
Response.Redirect("~/message.aspx");
}
}
From the MSDN Documentation:
If the host name could not be found, the SocketException exception is returned with a value of 11001 (Windows Sockets error WSAHOST_NOT_FOUND). This exception can be returned if the DNS server does not respond. This exception can also be returned if the name is not an official host name or alias, or it cannot be found in the database(s) being queried.
Therefore, I suspect your code isn't getting as far as the third if condition because an exception is being thrown by the call to GetHostEntry(), which you're seeing as the 'error "No Host Found" message'.
The most straightforward way to deal with this is to use a try...catch block to catch the specific exception and handle it, something such as:
try
{
deviceName = Dns.GetHostEntry(IPAddress.Parse(IPaddr)).HostName;
}
catch (SocketException)
{
deviceName = "Device name could be found";
}
This says that if a SocketException occurs during the call to GetHostEntry(), the code is to jump to the catch block, rather than the exception stopping your application.
Note that this assumes that any SocketException means that the IP address wasn't found, but it could mean that the DNS server wasn't contactable, or some other error.
MSDN has quite a lot on exception handling and how try...catch blocks work.
Hope this helps
Before you get a value from a dictionary, you must check if the dictionary contains the key you pass. You achieve this by calling "Contains" method.
if (HttpContext.Current.Request.ServerVariables.Contains("HTTP_X_FORWARDER_FOR"))
{
// Your Code...
}
If you retrieve the content of a dictionary directly and the key you are requesting doesn't exist in the dictionary pairs, the dictionary doesn't return null. Instead, it throws KeyNotFoundException.
I know this question that had been asked before but didn't find an appropriate solution to it yet! I hosted my website a few days ago. Everything works normally in my website a part of my contact form that it doesn't work!
The contact form itself doesn't show any errors whatsoever, in fact when I send the details I still get the label message that confirms of sending process, but nothing comes into my email.
The strange thing is when I talked to my host provider, he says to me that there is nothing wrong with my script and they didn't block any port.
I also ran the contact page and done the same process by filling all required fields and it works properly.Any help would much appreciated!
My code :
namespace contact
{
public partial class ContactUs : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new
ScriptResourceDefinition
{
Path = "~/scripts/jquery-1.9.1.js"
});
}
protected void btnSub_Click1(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
try
{
if (Page.IsValid)
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress(txtEmail.Text);
mail.To.Add("myemailaddress");
mail.Subject = txtSubject.Text;
mail.Body = "<b> Sender Name: </b>" + txtName.Text + "
<br/>"
+ "<b> Sender Email: </b>" + txtEmail.Text + "<br/>"
+ "<b> Sender Comment: </b>" + txtMessage.Text;
mail.IsBodyHtml = true;
SmtpClient smtpClient = new
SmtpClient("company's mail", 587);
smtpClient.EnableSsl = true;
smtpClient.Credentials = new
System.Net.NetworkCredential("myemailaddress","password");
smtpClient.Send(mail);
lblmsg.Text = "Thank you for contacting us";
txtName.Enabled = false;
txtEmail.Enabled = false;
txtSubject.Enabled = false;
txtMessage.Enabled = false;
btnSub.Enabled = false;
}
}
catch (Exception ex)
{
lblmsg.Text = "An unexpected error has occured! " + 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'm basically making a mass email sender in C# using Microsoft Visual Studio, the idea is that it uses real email accounts via SMTP to send the emails so they are not marked as spam, but I keep getting the error:
URI formats are not supported.
Basically the code below retrieves the list of email accounts from my website but throws the error above.
String[] saUsernames = File.ReadAllLines(#"http://mywebsite.com/test/accounts.txt");
I've tried loading the file locally and it works fine so i cant figure out what the issue is, anyone got any ideas as I'm well and truly confused
edit: heres the whole script as something else may be causing the error, ive removed some of the links to my site,etc as its a project in development and i dont want to give away many clues
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Mail;
using System.Threading;
using System.IO;
namespace NecroBomber
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int iTimeOutValue = 100;
int iSentAmount = 0;
SmtpClient client = new SmtpClient();
MailMessage mail = new MailMessage();
String[] saUsernames = File.ReadAllLines(#"http://example.com/accounts.txt");
WebClient wcUpdates = new WebClient();
string sMasterPassword = "testpassword";
string sLastUsername = "";
int iTimeOutWebRequest = 0;
private void btnClick(object sender, EventArgs e)
{
Button btnCurrent = ((Button)sender);
if (btnCurrent.Tag.ToString() == "SendMail")
{
prbSentStatus.Maximum = ((int)nudAmount.Value * saUsernames.Length);
Thread tStart = new Thread(SendMail);
tStart.Start();
}
else if (btnCurrent.Tag.ToString() == "AddAccount")
{
AddNewAccount();
}
else if (btnCurrent.Tag.ToString() == "Update")
{
try
{
if (wcUpdates.DownloadString(#"http://example.com/version.txt") != "1.0.0")
{
if (dlgSaveUpdate.ShowDialog() == DialogResult.OK)
{
wcUpdates.DownloadFile(#"http://example.com/new.exe", dlgSaveUpdate.FileName);
}
}
else
{
MessageBox.Show("Your version is up to date!", "Information!");
}
}
catch
{
}
}
}
private void SendMail()
{
int iToSend = Convert.ToInt32(nudAmount.Value);
for (int i = 0; i < saUsernames.Length; i++)
{
GrabMailDetails(i);
client.Credentials = new NetworkCredential(saUsernames[i], sMasterPassword);
if (saUsernames[i] != sLastUsername)
{
if (saUsernames[i].EndsWith("#yahoo.com"))
{
client.Host = "smtp.mail.yahoo.com";
client.Port = 587;
client.EnableSsl = false;
}
else if (saUsernames[i].EndsWith("#gmail.com"))
{
client.Host = "smtp.gmail.com";
client.Port = 25;
client.EnableSsl = true;
}
else if (saUsernames[i].EndsWith("#hotmail.co.uk"))
{
client.Host = "smtp.live.com";
client.Port = 587;
client.EnableSsl = true;
}
else if (saUsernames[i].EndsWith("#outlook.com"))
{
client.Host = "smtp.live.com";
client.Port = 587;
client.EnableSsl = true;
}
else if (saUsernames[i].EndsWith("#hotmail.com"))
{
client.Host = "smtp.live.com";
client.Port = 587;
client.EnableSsl = true;
}
else if (saUsernames[i].EndsWith("#aol.co.uk"))
{
client.Host = "smtp.aol.com";
client.Port = 587;
client.EnableSsl = true;
}
else if (saUsernames[i].EndsWith("#aol.com"))
{
client.Host = "smtp.aol.com";
client.Port = 587;
client.EnableSsl = true;
}
}
else
{
}
sLastUsername = saUsernames[i];
for (int x = 0; x < iToSend; x++)
{
try
{
client.Send(mail);
iSentAmount++;
}
catch
{
MessageBox.Show("Maximum emails today sent from this SMTP server has been reached.\nAccount name: " + sLastUsername, "Error!");
goto JMP;
}
}
JMP: ;
}
}
private void GrabMailDetails(int count)
{
try
{
mail = new MailMessage();
mail.Body = tbBody.Text;
mail.Subject = tbSubject.Text;
mail.From = new MailAddress(saUsernames[count]);
mail.To.Add(tbTarget.Text);
{
}
if (rbHigh.Checked)
{
mail.Priority = MailPriority.High;
}
else if (rbLow.Checked)
{
mail.Priority = MailPriority.Low;
}
else if (rbNorm.Checked)
{
mail.Priority = MailPriority.Normal;
}
}
catch
{
}
}
private void AddNewAccount()
{
String[] saCurrentAccounts = File.ReadAllLines(#"Accounts.txt");
string sAddNewAccount = "";
for (int i = 0; i < saCurrentAccounts.Length; i++)
{
sAddNewAccount += saCurrentAccounts[i] + Environment.NewLine;
}
}
private void timeUpdate_Tick(object sender, EventArgs e)
{
prbSentStatus.Value = iSentAmount;
lblEmailSentCount.Text = "Emails Sent: " + iSentAmount;
iTimeOutWebRequest++;
if (iTimeOutWebRequest == iTimeOutValue)
{
}
}
private void Form1_Load(object sender, EventArgs e)
{
timeUpdate.Start();
lblMultiple.Text = "x " + saUsernames.Length;
this.Text = "test - " + Environment.UserName;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
if (wcUpdates.DownloadString(#"update.com/version") != "1.0.0")
{
if (dlgSaveUpdate.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("Updating LulzBomber. Please wait a few minutes", "Information!");
wcUpdates.DownloadFile(#"update.com/version", dlgSaveUpdate.FileName);
}
}
else
{
MessageBox.Show("Your version is up to date!", "Information!");
}
}
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show("Created by ***", "About");
}
}
}
File.ReadAllLines does not support the http schema such as http.
Try instead:
string content;
using (WebClient client = new WebClient())
{
content = client.DownloadString("http://example.com/accounts.txt");
}
'content' will contain the complete contents of the file. Splitting the content into an array is trivial using the string.Split() function.
Note: WebClient can also reference local files from disk if referenced as such:
#"file://c:\folder\account.txt"
File.ReadAllLines does not support a direct URI path as stated in the error message (although it is puzzling how it is working locally), just allocate your path to a string then use that in the request.
string path = #"http://mywebsite.com/test/accounts.txt";
String[] saUsernames = File.ReadAllLines(path);
Edit: You could ditch the # as there are no characters to escape in your string and just use your original line.
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";
}
}