URI formats are not supported - c#

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.

Related

Memory leak is seen when SmtpClient send function called multiple times

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

How to add a Counter on my Bulk Mail Sender ASP.NET Windows App?

I have built a bulk Email Sender, but it shows a message after sending all the mails. I want to add a counter to the event that will show a message box with a Count that increment the number while sending the Mails. And after sending the mails a message will show the number of total sent mails and unsent mails.
Here is my C# code for the send mail event -
private void btnSendEmail_Click(object sender, EventArgs e)
{
string subject = txtSubject.Text;
string message = txtMessage.Text;
if (!txtFile.Text.Equals(String.Empty))
{
if (System.IO.Directory.GetFiles(txtFile.Text).Length > 0)
{
foreach (string file in System.IO.Directory.GetFiles(txtFile.Text))
{
}
}
else
{
}
}
var con = "Data Source=Ashiq-pc;Initial Catalog=OfferMails;Integrated Security=True;MultipleActiveResultSets=True";
List<EmailModel> emailList = new List<EmailModel>();
using (SqlConnection myConnection = new SqlConnection(con))
{
string oString = "Select * from tbl_MailAdd where Flag=#Flag";
SqlCommand oCmd = new SqlCommand(oString, myConnection);
oCmd.Parameters.AddWithValue("#Flag", true);
myConnection.Open();
using (SqlDataReader oReader = oCmd.ExecuteReader())
{
while (oReader.Read())
{
EmailModel emailModel = new EmailModel();
emailModel.ID = Convert.ToInt16(oReader["ID"]);
emailModel.EmailAdd = oReader["EmailAdd"].ToString();
emailModel.Flag = Convert.ToBoolean(oReader["Flag"]);
emailList.Add(emailModel);
}
myConnection.Close();
}
}
//return matchingPerson;
foreach (EmailModel email in emailList)
{
try
{
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.Port = 587;
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential("my mail", "my pass");
MailMessage msg = new MailMessage();
msg.To.Add(email.EmailAdd);
msg.From = new MailAddress("my from name");
msg.Subject = subject;
msg.Body = message;
if (!txtFile.Text.Equals(String.Empty))
{
if (System.IO.Directory.GetFiles(txtFile.Text).Length > 0)
{
foreach (string file in System.IO.Directory.GetFiles(txtFile.Text))
{
//Add file in ListBox.
listAttch.Items.Add(file);
//System.Windows.Forms.MessageBox.Show("Files found: " + file, "Message");
Attachment data = new Attachment(file);
msg.Attachments.Add(data);
}
}
else
{
//listBox1.Items.Add(String.Format(“No files Found at location : {0}”, textBox1.Text));
}
}
//Attachment data = new Attachment(textBox_Attachment.Text);
//msg.Attachments.Add(data);
client.Send(msg);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//for (int i = 0; i < emailList.Count; i++)
//{
// MessageBox.Show("i++");
//}
MessageBox.Show("Successfully Sent Message.");
}
If there's an immediate error, SmtpClient.Send() will throw an exception. There's no way to "track" the email (unless there's some confirmation link to click or whatever). You won't keep a server connection till the mail is received, only till your smtp server passed it successfully (or failed doing so).
So add a simple int counter = 0; outside your main foreach loop and increment after each call to smtpclient.Send()
or
Add a bool Sent field to your EmailModel. After each call to smtpclient.Send() update this to true.
Afterwards count the number of EMailModels where the Sent field is set to true.
public class EMailModel
{
int Id;
int EmailAdd;
bool Flag;
bool Sent;
}
...
foreach (EmailModel email in emailList)
{
...
client.Send(msg);
email.Sent = true;
}
...
int noOfUnsentEmails = emailList.Count(x => x.Sent == false);
int noOfSentEmails = emailList.Count(x => x.Sent == true);

How to get the file in byte[] in c# windows form using openfile dialog

I want to retrieve mail attachments and store them into bytes[] so that I can insert them into table where a column attachment is of varbinary type. In windows form I am using OpenFileDialog and I don't know how to get the file's bytes in a byte[] type so that I can insert that into table in SQLServer.
Here is the code:
namespace fyp8
{
public partial class ComposeMail : Form1
{
ArrayList alAttachments;
MailMessage mmsg;
string conn = #"Data source=(local);Initial Catalog=fyp;Integrated Security=true";
public ComposeMail()
{
InitializeComponent();
}
private void ComposeMail_Load(object sender, EventArgs e)
{
}
private void btnAttachment_Click(object sender, EventArgs e)
{
OpenFileDialog odflg = new OpenFileDialog();
odflg.ShowDialog();
if (odflg.ShowDialog() == DialogResult.OK)
{
try
{
txtAttachments.Text = odflg.FileName;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
}
private void btnSend_Click(object sender, EventArgs e)
{
try
{
if (txtEmid.Text != null && txtPass.Text != null)
{
mmsg = new MailMessage(txtEmid.Text, txtTo.Text);
mmsg.Subject = txtSub.Text;
mmsg.Body = txtBody.Text;
mmsg.IsBodyHtml = true;
/* Set the SMTP server and send the email with attachment */
SmtpClient smtpClient = new SmtpClient();
// smtpClient.Host = emailServerInfo.MailServerIP;
//this will be the host in case of gamil and it varies from the service provider
smtpClient.Host = "smtp.gmail.com";
//smtpClient.Port = Convert.ToInt32(emailServerInfo.MailServerPortNumber);
//this will be the port in case of gamil for dotnet and it varies from the service provider
smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = true;
//smtpClient.Credentials = new System.Net.NetworkCredential(emailServerInfo.MailServerUserName, emailServerInfo.MailServerPassword);
smtpClient.Credentials = new NetworkCredential(txtEmid.Text, txtPass.Text);
//Attachment
Attachment attachment = new Attachment(txtAttachments.Text);
if (attachment != null)
{
mmsg.Attachments.Add(attachment);
}
//this will be the true in case of gamil and it varies from the service provider
smtpClient.EnableSsl = true;
smtpClient.Send(mmsg);
}
string msg = "Message Send Successfully:";
msg += "\n To :" + txtTo.Text;
SqlConnection con = new SqlConnection(conn);
string query = "insert into sentmail values(#from,#to,#sub,#body,#status)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#from", txtFrom.Text);
cmd.Parameters.AddWithValue("#to", txtTo.Text);
cmd.Parameters.AddWithValue("#sub", txtSub.Text);
cmd.Parameters.AddWithValue("#body",txtBody.Text);
cmd.Parameters.AddWithValue("#status","sent" );
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show(msg.ToString());
/* clear the controls */
txtEmid.Text = string.Empty;
txtPass.Text = string.Empty;
txtFrom.Text = string.Empty;
txtTo.Text = string.Empty;
txtSub.Text = string.Empty;
txtBody.Text = string.Empty;
txtAttachments.Text = string.Empty;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
}
Use the FileDialog.FileName property to get the selected file name.
Use File.ReadAllBytes to easily read the entire file into a byte array.
void Test() {
var dialog = new OpenFileDialog();
var result = dialog.ShowDialog();
if (result != DialogResult.OK)
return;
byte[] buffer = File.ReadAllBytes(dialog.FileName);
// Do whatever you want here with buffer
}
You're currently calling ShowDialog() twice. Just call it once and save the result.

Need help making and waiting for a reocurring event

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.

Need to send email using background worker process

I have code written for sending email in C#, but the application hangs up when the application is sending mails size of attachments more than 2 MB. I was advised to use background worker process for the same by SO users.
I have gone thru the background worker process example from MSDN and google it also, but i don't know how to integrate in my code.
Please guide me in that...
thanks
UPDATED: Email-Code Added
public static void SendMail(string fromAddress, string[] toAddress, string[] ccAddress, string[] bccAddress, string subject, string messageBody, bool isBodyHtml, ArrayList attachments, string host, string username, string pwd, string port)
{
Int32 TimeoutValue = 0;
Int32 FileAttachmentLength = 0;
{
try
{
if (isBodyHtml && !htmlTaxExpression.IsMatch(messageBody))
isBodyHtml = false;
// Create the mail message
MailMessage objMailMsg;
objMailMsg = new MailMessage();
if (toAddress != null) {
foreach (string toAddr in toAddress)
objMailMsg.To.Add(new MailAddress(toAddr));
}
if (ccAddress != null) {
foreach (string ccAddr in ccAddress)
objMailMsg.CC.Add(new MailAddress(ccAddr));
}
if (bccAddress != null) {
foreach (string bccAddr in bccAddress)
objMailMsg.Bcc.Add(new MailAddress(bccAddr));
}
if (fromAddress != null && fromAddress.Trim().Length > 0) {
//if (fromAddress != null && fromName.trim().length > 0)
// objMailMsg.From = new MailAddress(fromAddress, fromName);
//else
objMailMsg.From = new MailAddress(fromAddress);
}
objMailMsg.BodyEncoding = Encoding.UTF8;
objMailMsg.Subject = subject;
objMailMsg.Body = messageBody;
objMailMsg.IsBodyHtml = isBodyHtml;
if (attachments != null) {
foreach (string fileName in attachments) {
if (fileName.Trim().Length > 0 && File.Exists(fileName)) {
Attachment objAttachment = new Attachment(fileName);
FileAttachmentLength=Convert.ToInt32(objAttachment.ContentStream.Length);
if (FileAttachmentLength >= 2097152) {
TimeoutValue = 900000;
} else {
TimeoutValue = 300000;
}
objMailMsg.Attachments.Add(objAttachment);
//objMailMsg.Attachments.Add(new Attachment(fileName));
}
}
}
//prepare to send mail via SMTP transport
SmtpClient objSMTPClient = new SmtpClient();
if (objSMTPClient.Credentials != null) { } else {
objSMTPClient.UseDefaultCredentials = false;
NetworkCredential SMTPUserInfo = new NetworkCredential(username, pwd);
objSMTPClient.Host = host;
objSMTPClient.Port = Int16.Parse(port);
//objSMTPClient.UseDefaultCredentials = false;
objSMTPClient.Credentials = SMTPUserInfo;
//objSMTPClient.EnableSsl = true;
//objSMTPClient.DeliveryMethod = SmtpDeliveryMethod.Network;
}
//objSMTPClient.Host = stmpservername;
//objSMTPClient.Credentials
//System.Net.Configuration.MailSettingsSectionGroup mMailsettings = null;
//string mailHost = mMailsettings.Smtp.Network.Host;
try {
objSMTPClient.Timeout = TimeoutValue;
objSMTPClient.Send(objMailMsg);
//objSMTPClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
objMailMsg.Dispose();
}
catch (SmtpException smtpEx) {
if (smtpEx.Message.Contains("secure connection")) {
objSMTPClient.EnableSsl = true;
objSMTPClient.Send(objMailMsg);
}
}
}
catch (Exception ex)
{
AppError objError = new AppError(AppErrorType.ERR_SENDING_MAIL, null, null, new AppSession(), ex);
objError.PostError();
throw ex;
}
}
}
I can't modify the code here as it is common method that is called whenever mail is to be sent from my application.
You could start a background thread to continuously loop and send email:
private void buttonStart_Click(object sender, EventArgs e)
{
BackgroundWorker bw = new BackgroundWorker();
this.Controls.Add(bw);
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.RunWorkerAsync();
}
private bool quit = false;
void bw_DoWork(object sender, DoWorkEventArgs e)
{
while (!quit)
{
// Code to send email here
}
}
Alternative way to do it:
private void buttonStart_Click(object sender, EventArgs e)
{
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
client.SendCompleted += new System.Net.Mail.SendCompletedEventHandler(client_SendCompleted);
client.SendAsync("from#here.com", "to#there.com", "subject", "body", null);
}
void client_SendCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error == null)
MessageBox.Show("Successful");
else
MessageBox.Show("Error: " + e.Error.ToString());
}
Specific to your example, you should replace the following:
try
{
objSMTPClient.Timeout = TimeoutValue;
objSMTPClient.Send(objMailMsg);
//objSMTPClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
objMailMsg.Dispose();
}
catch (SmtpException smtpEx)
{
if (smtpEx.Message.Contains("secure connection"))
{
objSMTPClient.EnableSsl = true;
objSMTPClient.Send(objMailMsg);
}
}
with the following:
objSMTPClient.Timeout = TimeoutValue;
objSMTPClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
objSMTPClient.SendAsync(objMailMsg, objSMTPClient);
and further down, include:
void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
if (e.Error == null)
MessageBox.Show("Successful");
else if (e.Error is SmtpException)
{
if ((e.Error as SmtpException).Message.Contains("secure connection"))
{
(e.UserState as SmtpClient).EnableSsl = true;
(e.UserState as SmtpClient).SendAsync(objMailMsg, e.UserState);
}
else
MessageBox.Show("Error: " + e.Error.ToString());
}
else
MessageBox.Show("Error: " + e.Error.ToString());
}
There's a great example of how to do this with a "Service Broker" in Chapter 8 of Richard Kiessig's book "Ultra-Fast ASP.NET."
Here's the link to the book on the publisher's website where you can download the sample code from the book. Again, chapter 8...
http://apress.com/book/view/9781430223832

Categories

Resources