I have to send mails multiple times, when this is done multiple times by using smtpclient class, Memory is increasing drastically......
I have tried with following things...
- Calling dispose methods for MailMessage, smtpclient
- calling GC.collect method manually
Nothing helped me...
using System;
using System.Net.Mail;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
using (var smtpobj = new SmtpClient("smtp.gmail.com"))
{
mail.To.Add("xxx#gmail.com");
mail.From = new MailAddress("yyy#gmail.com");
mail.Subject = "subject - .net app";
mail.Body = "body";
smtpobj.Port = 587;
smtpobj.Credentials = new System.Net.NetworkCredential("yyy#gmail.com", "xyz");
smtpobj.EnableSsl = true;
smtpobj.Send(mail);
}
}
catch(Exception ex)
{
string strReturn = ex.ToString();
MessageBox.Show(strReturn);
}
}
}
}
Try the following:
using System;
using System.Net.Mail;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
using (var smtpobj = new SmtpClient("smtp.gmail.com"))
{
mail.To.Add("xxx#gmail.com");
mail.From = new MailAddress("yyy#gmail.com");
mail.Subject = "subject - .net app";
mail.Body = "body";
smtpobj.Port = 587;
smtpobj.Credentials = new System.Net.NetworkCredential("yyy#gmail.com", "xyz");
smtpobj.EnableSsl = true;
smtpobj.Send(mail);
smtpobj.ServicePoint.CloseConnectionGroup(
smtpobj.ServicePoint.ConnectionName);
}
}
catch(Exception ex)
{
string strReturn = ex.ToString();
MessageBox.Show(strReturn);
}
}
}
}
This is per: https://social.msdn.microsoft.com/Forums/vstudio/en-US/28b59c25-bc93-4285-860d-52f1f49d2d43/net-smtp-class-memory-leakage?forum=netfxbcl
Related
I am trying to send a keycode through email but everytime I am getting this error:- "The server rejected the sender address. The server response was: 530 5.7.0 Must issue a STARTTLS command first. e6sm29167643pfj.71 - gsmtp. ". I think the problem is with the SendMails() but I am not getting what is that problem.Please help me out.I am using Visual studio community 2015?
Below is the code :-
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.Mail;
using System.Web.Util;
public partial class admin_ExamSchedule : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
int examtypeid = Convert.ToInt32(Session["examtypeid"].ToString());
ddlExamIdNotAttempted.DataSource = objAttemptexam.getNotAttemptedExamId(examtypeid);
ddlExamIdNotAttempted.DataValueField = "ExamId";
ddlExamIdNotAttempted.DataTextField = "ExamName";
ddlExamIdNotAttempted.DataBind();
// Response.Write("<script>alert('Must Select Any One')</script>");
//ddlExamIdAttempted.DataSource = objAttemptexam.getAttemptedExamId();
//ddlExamIdAttempted.DataValueField = "ExamId";
//ddlExamIdAttempted.DataTextField = "ExamName";
//ddlExamIdAttempted.DataBind();
}
}
BALexam objAttemptexam = new BALexam();
protected void btnSubmit_Click(object sender, EventArgs e)
{
try
{
objAttemptexam.uid = Convert.ToInt32(Session["uid"].ToString());
objAttemptexam.ExamReqDate = Convert.ToDateTime(Session["preferdate"]).ToString();
objAttemptexam.ExamAssignDate =txtAssignExamDate.Text;
objAttemptexam.ExamId = Convert.ToInt32(ddlExamIdNotAttempted.SelectedValue);
objAttemptexam.ExamRequestId = Convert.ToInt32(Session["ExamRequestId"].ToString());
// objAttemptexam.UserName = Session["User"].ToString();
objAttemptexam.KeyCode = txtKeyCode.Text;
string strMsg;
SendMails();
int i = objAttemptexam.InsertScheduleExam(out strMsg);
if (i > 1)
{
ClearData();
LblMsg.Text = strMsg;
}
else
LblMsg.Text = strMsg;
}
catch (Exception ex)
{
LblMsg.Text = ex.Message;
}
}
void SendMails()
{
MailMessage objMail = new MailMessage();
objMail.From = "abc27#gmail.Com";
objMail.To = "def4444#gmail.com";
objMail.Subject = "OnLineExam Schedule.";
objMail.BodyFormat = MailFormat.Html;
objMail.Body = "Your Key : " + txtKeyCode.Text + "" + "\n" +
"Your ExamId : " + Convert.ToInt32(ddlExamIdNotAttempted.SelectedValue) + "" + "\n" +
"Your ExamDate : " + txtAssignExamDate.Text;
SmtpMail.SmtpServer = "smtp.gmail.com";
SmtpMail.Send(objMail);
Page.RegisterClientScriptBlock("Dhanush", "<script>alert('Key Send to Student Successfully...')</script>");
}
private void ClearData()
{
txtAssignExamDate.Text = txtKeyCode.Text = "";
}
protected void ddlExamIdAttempted_DataBound(object sender, EventArgs e)
{
ddlExamIdNotAttempted.Items.Insert(0, "--Select--");
}
protected void ddlExamIdNotAttempted_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void LB_Click(object sender, EventArgs e)
{
Response.Redirect("frmShowExamRequest.aspx");
}
}
Just check your error message, it clearly states the Problem: you don't use a secure connection and Gmail does not allow to send over an insecure connection.
By the way: The SmtpMail class is deprecated and it is recommended to use System.Net.SmtpClient instead.
I would like to send an automated email message using c# and outlook. I am confused how to actually send the email, i thought the .Send() method would execute this but nothing happens when i run this and i do not get any compilation errors.
Does anyone know how to activate/execute this code or know somewhere I am messing up. Thank you.
using System;
using System.Management;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections;
using System.Net.Mail;
using System.Net.NetworkInformation;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Outlook;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace email
{
class Program
{
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
SendEmailtoContacts();
}
private void SendEmailtoContacts()
{
string subjectEmail = "test results ";
string bodyEmail = "test results";
Microsoft.Office.Interop.Outlook.Application appp = new
Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MAPIFolder sentContacts =
appp.ActiveExplorer().Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.O lDefaultFolders.olFolderContacts);
foreach (Outlook.ContactItem contact in sentContacts.Items)
{
if (contact.Email1Address.Contains("gmail.com"))
{
this.CreateEmailItem(subjectEmail, contact.Email1Address, bodyEmail);
}
}
}
private void CreateEmailItem(string subjectEmail,string toEmail, string bodyEmail)
{
Microsoft.Office.Interop.Outlook.Application app = new
Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem eMail =
app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
eMail.Subject = subjectEmail;
eMail.To = toEmail;
eMail.Body = bodyEmail;
eMail.Importance = Outlook.OlImportance.olImportanceLow;
((Outlook._MailItem)eMail).Send();
}
static void Main(string[] args)
{
}
}
}
///////////////////////////////////////////////////////////
CORRECT CODE:
using System;
using System.Management;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections;
using System.Net.Mail;
using System.Net.NetworkInformation;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Outlook;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace email
{
class Program
{
static void Main(string[] args)
{
SendEmailtoContacts();
CreateEmailItem("yo", "EMAIL#WHATEVER.COM", "yoyoyoyoyo");
}
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
SendEmailtoContacts();
}
private static void SendEmailtoContacts()
{
string subjectEmail = "test results ";
string bodyEmail = "test results";
Microsoft.Office.Interop.Outlook.Application appp = new
Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MAPIFolder sentContacts =
appp.ActiveExplorer().Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.O
lDefaultFolders.olFolderContacts);
foreach (Outlook.ContactItem contact in sentContacts.Items)
{
if (contact.Email1Address.Contains("gmail.com"))
{
CreateEmailItem(subjectEmail, contact.Email1Address,
bodyEmail);
}
}
}
private static void CreateEmailItem(string subjectEmail, string
toEmail, string bodyEmail)
{
Microsoft.Office.Interop.Outlook.Application app = new
Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem eMail =
app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
eMail.Subject = subjectEmail;
eMail.To = toEmail;
eMail.Body = bodyEmail;
eMail.Importance = Outlook.OlImportance.olImportanceLow;
((Outlook._MailItem)eMail).Send();
}
}
}
Your question title says "c# console app to send email automatically" but you appear to be using code that was meant for an Outlook AddIn. The addin is meant to call the SendEmail function upon startup of the addin which would execute ThisAddIn_Startup:
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
// this is never executed because it isn't an outlook addin
SendEmailtoContacts();
}
private void SendEmailtoContacts()
{
// sends your email... if it actually gets called
}
Instead try calling that SendEmailtoContacts() function from your Main() because it is a console app and Main() is what is actually executed when you run it:
static void Main(string[] args)
{
SendEmailtoContacts();
}
For further debugging, as I noted in a comment, because this is outlook interop you should be able to see these operations taking place in an outlook window as they are executed on your local desktop. For example, if you comment out the final ((Outlook._MailItem)eMail).Send(); line and run the program you should be left with an email waiting for you to click the send button after your program terminates.
It looks like you'll also have to modify the method signatures of the other functions to static methods and get rid of the this reference in this.CreateEmailItem?
public static void SendEmailtoContacts()
{
string subjectEmail = "test results ";
string bodyEmail = "test results";
Microsoft.Office.Interop.Outlook.Application appp = new
Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MAPIFolder sentContacts =
appp.ActiveExplorer().Session.GetDefaultFolder(Microsoft.Office.Interop.Outlook.O lDefaultFolders.olFolderContacts);
foreach (Outlook.ContactItem contact in sentContacts.Items)
{
if (contact.Email1Address.Contains("gmail.com"))
{
CreateEmailItem(subjectEmail, contact.Email1Address, bodyEmail);
}
}
}
public static void CreateEmailItem(string subjectEmail,string toEmail, string bodyEmail)
{
Microsoft.Office.Interop.Outlook.Application app = new
Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem eMail =
app.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
eMail.Subject = subjectEmail;
eMail.To = toEmail;
eMail.Body = bodyEmail;
eMail.Importance = Outlook.OlImportance.olImportanceLow;
((Outlook._MailItem)eMail).Send();
}
you could use SMTP to do this
using System.Net;
using System.Net.Mail;
using System.Configuration;
static void Main(string[] args)
{
SendEmail("Lukeriggz#gmail.com", "This is a Test email", "This is where the Body of the Email goes");
}
public static void SendEmail(string sTo, string subject, string body)
{
var Port = int.Parse(ConfigurationManager.AppSettings["SmtpPort"]);
using (var client = new SmtpClient(Your EmailHost, Port))
using (var message = new MailMessage()
{
From = new MailAddress(FromEmail),
Subject = subject,
Body = body
})
{
message.To.Add(sTo);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["EmailCredential"],
ConfigurationManager.AppSettings["EmailPassword"]);
client.EnableSsl = true;
client.Send(message);
};
}
if you want a list of contacts to send the same email then create a List<string> and using a foreach loop add them to the message.To.Add(sTo) portion of the code.. pretty straight forward..
if you insist on using Outlook to send emails then looks at this MSDN link
Programmatically Send E-Mail Programmatically
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 am having multiple problems, there are going to be multiple usernames and passwords in the listbox...
I need the application to wait while and account is in the text boxes, and then when the textboxes are clear then the account next in the listbox can go to the next line..
Here is the code
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.IO;
using System.Net.Mail;
using System.Net;
using System.Text.RegularExpressions;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnOpenFile_Click(object sender, EventArgs e)
{
this.lbAccounts.Items.Clear();
OpenFileDialog Open = new OpenFileDialog();
Open.Title = "Select Email List";
Open.Filter = "Text Document|*.txt|All Files|*.*";
try
{
Open.ShowDialog();
StreamReader Import = new StreamReader(Convert.ToString(Open.FileName));
while (Import.Peek() >= 0)
lbAccounts.Items.Add(Convert.ToString(Import.ReadLine()));
}
catch (Exception)
{
}
}
private void SendTestMail()
{
try
{
NetworkCredential loginInfo = new NetworkCredential(txtUser.Text, txtPass.Text);
MailMessage msg = new MailMessage();
msg.From = new MailAddress(txtUser.Text);
msg.To.Add(new MailAddress("example#gmail.com"));
msg.Subject = "Hi, I'm Valid :D";
msg.Body = txtUser.Text + ":" + txtPass.Text;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
client.Send(msg);
lbGoodAccounts.Items.Add(txtUser.Text + ":" + txtPass.Text);
txtUser.Clear();
txtPass.Clear();
}
catch (Exception)
{
lbFailAccounts.Items.Add(txtUser.Text + ":" + txtPass.Text);
txtUser.Clear();
txtPass.Clear();
}
}
private void btnCheck_Click(object sender, EventArgs e)
{
SendTestMail();
}
private void btnExport_Click(object sender, EventArgs e)
{
StreamWriter Write;
SaveFileDialog Open = new SaveFileDialog();
try
{
Open.Filter = ("Text Document|*.txt|All Files|*.*");
Open.FileName = ("Good Gmail Accounts");
Open.ShowDialog();
Write = new StreamWriter(Open.FileName);
for (int I = 0; I < lbGoodAccounts.Items.Count; I++)
{
Write.WriteLine(Convert.ToString(lbGoodAccounts.Items[I]));
}
Write.Close();
}
catch (Exception ex)
{
MessageBox.Show(Convert.ToString(ex.Message));
return;
}
}
}
}
If I understood you right this is the code you will need :
void AccountsListBox_Click (object sender, EventArgs args)
{
if (AccountsListBox.SelectedIndex < 0)
return;
if (!string.IsNullOrEmpty(TextBoxName.Text) && !string.IsNullOrEmpty(TextBoxPass.Text))
return; // stop processing if they have some data
// otherwise get acccount:password,
// split it into acc and pass and write them to TextBoxes
string value = AccountsListBox.Items[AccountsListBox.SelectedIndex];
string[] values = value.Split(':');
if (values.Length != 2)
return; // wrong format
var acc = values[0];
var pass = values[1];
TextBoxName.Text = acc;
TextBoxPass.Text = pass;
}
I haven't used WinForms for some time so if you find some errors please correct them :)
See MSDN ListBox documentation for details.
I`m working with C# using the libraries
using System.Net.Mail;
using System.Windows;
I want to use the code in many places, ie. place A, place B, place C ...
when I use it at place A, it works and mails are sent from my application.
but when I use it at place B, place C ... nothing is sent and I get errors, I want to know how to solve it.
this is my class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Windows;
namespace Send_Mail_WPF_
{
class SendMail
{
private string fromAddress;
private string fromPassword;
private string toAddress;
private string msgSubject;
private string msgBody;
private string exchangeServer;
private int exchangeServerPort;
private bool error;
private MailMessage message;
SmtpClient client;
public SendMail(string fromMail, string toMail, string fromPass, string subject, string body)
{
error = false;
try
{
fromAddress = fromMail.ToString();
toAddress = toMail.ToString();
fromPassword = fromPass.ToString();
msgSubject = subject.ToString();
msgBody = body.ToString();
exchangeServer = #"smtp.tedata.net";
exchangeServerPort = 25;
initializeMessage();
setSMTPClient();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
errorFound = true;
}
}
public bool errorFound
{
set
{
error = value;
}
get
{
return error;
}
}
private void initializeMessage()
{
message = new MailMessage(fromAddress, toAddress);
message.Subject = msgSubject;
message.Body = msgBody;
message.IsBodyHtml = false;
}
private void setSMTPClient()
{
try
{
client = new SmtpClient(exchangeServer, exchangeServerPort);
client.EnableSsl = false;
client.Credentials = new NetworkCredential(fromAddress, fromPassword);
MessageBox.Show("From" + message.From.ToString());
message.From = new MailAddress("aaaaaaaa#aaaaaaaaaaaaa.com");
MessageBox.Show("From" + message.From.ToString());
Application.Current.Shutdown();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
errorFound = true;
}
}
public void sendMessage()
{
try
{
client.Send(message);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
errorFound = true;
}
}
}
}
I think the problem is in the exchange server, but I don`t know how to over come this.
EDIT:
ERROR I get from any location rather than place A
alt text http://img651.imageshack.us/img651/6343/errorh.jpg
By the different places, I take it you mean different machines. The problem is likely DNS, or some other problem external to your code. A good way to test SMTP connectivity is to telnet to smtp.tedata.net on port 25. I'm guessing that won't work, which explains why your code doesn't work either. Once you've solved the network issue, retry your code.
Your code is OK. This is probably an authentication issue. Check with your network administrator.
Difference places means different Ip address.
sometimes SMTP service is set to work only in limited ip pool.
In your case, it is likely your SMTP service would only work in Place A's IP address, but not in Place B, and Place C