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
Related
So I have searched a lot of areas for this answer and I am confused on what this error is doing. Whenever I press the start server button...
...I get this error "An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dll"
My code is quite long but I have no clue what to do...
using System;
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.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
private bool isserver = false;
public const int MAXSIZE = 10;
public Form1()
{
InitializeComponent();
clearoutput();
}
TcpListener tcpl = new TcpListener(IPAddress.Parse(getip()), 2546);
List<TcpClient> clients = new List<TcpClient>();
List<string> names = new List<string>();
bool CommandMode = false;
List<string> banlist = new List<string>();
TcpClient Client = new TcpClient();
//client setup
private void button1_Click(object sender, EventArgs e)
{
try {
Output.Text = Output.Text + "You have joined as a client";
Client = new TcpClient();
Client.Connect(IP_address.Text, 2546);
Thread myThread = new Thread(new ParameterizedThreadStart(Listen));
myThread.Start(Client);
//whenever you send a message you must include the next two lines
//Client.GetStream().Write(new byte[] { (byte)Encoding.Unicode.GetByteCount(name + " has joined") }, 0, 1);
//Client.GetStream().Write(Encoding.Unicode.GetBytes(name + " has joined"), 0, Encoding.Unicode.GetByteCount(name + " has joined"));
//the two lines above
Client.GetStream().Write(new byte[] { (byte)Encoding.Unicode.GetByteCount("\\join" + getip()) }, 0, 1);
Client.GetStream().Write(Encoding.Unicode.GetBytes("\\join" + getip()), 0, Encoding.Unicode.GetByteCount("\\join" + getip()));
}
catch { }
IP_address.Visible = false;
Join_btn.Visible = false;
Start_btn.Visible = false;
Output.Visible = true;
Input.Visible = true;
text1.Visible = true;
text1.Visible = true;
}
private void clearoutput()
{
Output.Text = "";
}
//server setup---
private void Start_btn_Click(object sender, EventArgs e)
{
isserver = true;
server_IP_lbl.Text = $"Since you are a server:\nYour ip address is : "+getip();
//if You need a new banlist make sure you click here and allow this
Write_to_output("you are a server");
try
{
StreamReader readerfrban = new StreamReader("banlist");
readerfrban.Close();
Write_to_output("we found a banlist \n no worries");
}
catch
{
Write_to_output("Error- could not find a banlist creating one now");
StreamWriter banlistmaker = new StreamWriter("banlist");
banlistmaker.Close();
}
//open banlist
StreamReader readerforban = new StreamReader("banlist");
string reader = "";
//read all bans in
do
{
reader = readerforban.ReadLine();
if (reader != null)
banlist.Add(reader);
} while (reader != null);
tcpl.Start();
//Thread AcceptSocketsThread = new Thread(AcceptSockets);
//AcceptSocketsThread.Start();
/* while (true)
{
string Message = Console.ReadLine();
if (Message.StartsWith("\\Kick"))
{
Console.Clear();
CommandMode = true;
int clientID = 0;
foreach (TcpClient client in clients)
{
Write_to_output(clientID.ToString() + ") " + names[clientID] + " " + client.Client.RemoteEndPoint);
clientID++;
}
Write_to_output("\n\n Enter the number of the person you want to kick");
TcpClient toRemove = clients[Convert.ToInt32(Console.ReadLine())];
toRemove.Close();
clients.Remove(toRemove);
CommandMode = false;
}
else if (Message.StartsWith("\\Reset"))
{
foreach (TcpClient client in clients)
{
client.Close();
}
clients.Clear();
Write_to_output("KICKED EVERY BODY");
}
else if (Message.StartsWith("\\ban"))
{
Console.Clear();
CommandMode = true;
int clientID = 0;
foreach (TcpClient client in clients)
{
Write_to_output(clientID.ToString() + ") " + names[clientID] + " " + client.Client.RemoteEndPoint);
clientID++;
}
Write_to_output("\n\n Enter the number of the person you want to kick and ban");
TcpClient toRemove = clients[Convert.ToInt32(Console.ReadLine())];
banlist.Add(toRemove.Client.RemoteEndPoint.ToString().Split(new char[] { ':' })[0]);
toRemove.Close();
clients.Remove(toRemove);
CommandMode = false;
}
//starts game
else
{
foreach (TcpClient client in clients)
{
SendMessage(Message, client);
}
}
}*/
IP_address.Visible = false;
Join_btn.Visible = false;
Start_btn.Visible = false;
Output.Visible = true;
Input.Visible = true;
text1.Visible = true;
text1.Visible = true;
}
void SendMessage(string message, TcpClient reciever)
{
try {
reciever.GetStream().Write(new byte[] { (byte)Encoding.Unicode.GetByteCount(message) }, 0, 1);
reciever.GetStream().Write(Encoding.Unicode.GetBytes(message), 0, Encoding.Unicode.GetByteCount(message));
}
catch
{
Write_to_output("Was unable to send to any users error code 1.0.0.0");
}
}
void AcceptSockets()
{
while (true)
{
TcpClient client = tcpl.AcceptTcpClient();
Thread myThread = new Thread(new ParameterizedThreadStart(Listen));
clients.Add(client);
myThread.Start(client);
}
}
void setname(string name)
{
names.Add(name);
}
void Listen(object obj)
{
TcpClient TCPClient = (TcpClient)obj;
while (true)
{
try
{
byte[] fBuffer = new byte[1];
TCPClient.GetStream().Read(fBuffer, 0, 1);
byte[] buffer = new byte[(int)fBuffer[0]];
TCPClient.GetStream().Read(buffer, 0, (int)fBuffer[0]);
string message = Encoding.Unicode.GetString(buffer).Trim();
if (message.StartsWith("\\join"))
{
message = message.Remove(0, 5);
int a = 0;
for (int i = 0; i < banlist.Count; i++)
{
if (message.StartsWith(banlist[i]))
{
a = 1;
}
}
if (a == 0)
{
//int namespaceer = 0;
//foreach (char chars in message)
//{
// namespaceer += 1;
// if (chars == '+')
// break;
//}
// message = message.Remove(0, namespaceer);
}
else
{
//Write_to_output("Person on banlist");
// TcpClient toRemove = clients[Convert.ToInt32(Console.ReadLine())];
//toRemove.Close();
}
}
else
{
foreach (TcpClient client in clients)
{
if (client != TCPClient)
{
SendMessage(message, client);
}
}
if (!CommandMode)
{
Write_to_output(message.Trim());
}
else
{
}
}
}
catch (Exception e)
{
Write_to_output(e.ToString());
}
}
}
static string getip()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily.ToString() == "InterNetwork")
{
localIP = ip.ToString();
}
}
return localIP;
}
public void Write_to_output(string towrite)
{
//check outputs length
int numLines = 0;
string text = Output.Text;
numLines = Text.Split('\n').Length;
if (numLines == MAXSIZE)
{
Output.Text = towrite;
}
else
{
Output.Text = Output.Text + $"\n" + towrite;
}
}
private void Input_Leave(object sender, EventArgs e)
{
string message = Input.Text;
if (isserver == false)
{
//send client code
SendMessage(message,Client);
}
else
{
//send server code
foreach (TcpClient client in clients)
{
SendMessage(message, client);
}
}
}
}
}
Please help me...
Check if the port TCP 2546 is not busy by another process or code instance on the listening machine.
Or choose another free port to listen to.
On my windows phone 7 Mango app I use the Microsoft.Live and Microsoft.Live.Controls references to download and upload on Skydrive. Logging in and uploading files works fine but whenever I call the "client.GetAsync("/me/skydrive/files");" on the LiveConnectClient the Callback result is empty just containing the error: "An error occurred while retrieving the resource. Try again later."
I try to retrieve the list of files with this method.
This error suddenly occured without any change on the source code of the app (I think..) which worked perfectly fine for quite a while until recently. At least I didn't change the code section for up- or downloading.
I tried out the "two-step verification" of Skydrive, still the same: can log in but not download.
Also updating the Live refercences to 5.5 didn't change anything.
Here is the code I use. The error occurs in the "getDir_Callback" in the "e" variable.
Scopes (wl.skydrive wl.skydrive_update) and clientId are specified in the SignInButton which triggers "btnSignin_SessionChanged".
private void btnSignin_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
connected = true;
processing = true;
client = new LiveConnectClient(e.Session);
client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(UploadCompleted);
client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnDownloadCompleted);
client.DownloadProgressChanged += new EventHandler<LiveDownloadProgressChangedEventArgs>(client_DownloadProgressChanged);
infoTextBlock.Text = "Signed in. Retrieving file IDs...";
client.GetAsync("me");
}
else
{
connected = false;
infoTextBlock.Text = "Not signed into Skydrive.";
client = null;
}
}
private void OnGetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
if (e.Error == null)
{
client.GetCompleted -= new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.GetCompleted += getDir_Callback;
client.GetAsync("/me/skydrive/files");
client_id = (string)e.Result["id"];
if (e.Result.ContainsKey("first_name") && e.Result.ContainsKey("last_name"))
{
if (e.Result["first_name"] != null && e.Result["last_name"] != null)
{
infoTextBlock.Text = "Hello, " +
e.Result["first_name"].ToString() + " " +
e.Result["last_name"].ToString() + "!";
}
}
else
{
infoTextBlock.Text = "Hello, signed-in user!";
}
}
else
{
infoTextBlock.Text = "Error calling API: " +
e.Error.ToString();
}
processing = false;
}
public void getDir_Callback(object s, LiveOperationCompletedEventArgs e)
{
client.GetCompleted -= getDir_Callback;
//filling Dictionary with IDs of every file on SkyDrive
if (e.Result != null)
ParseDir(e);
if (!String.IsNullOrEmpty(e.Error.Message))
infoTextBlock.Text = e.Error.Message;
else
infoTextBlock.Text = "File-IDs loaded";
}
Yo shall use client.GetAsync("me/SkyDrive/files", null) in place of client.GetAsync("me");
This is my code and it works fine.
private void btnSignIn_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
try
{
if (e.Session != null && e.Status == LiveConnectSessionStatus.Connected)
{
client = new LiveConnectClient(e.Session);
client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(client_GetCompleted);
client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(client_UploadCompleted);
client.GetAsync("me/SkyDrive/files", null);
client.DownloadAsync("me/SkyDrive", null);
canUpload = true;
ls = e.Session;
}
else
{
if (client != null)
{
MessageBox.Show("Signed out successfully!");
client.GetCompleted -= client_GetCompleted;
client.UploadCompleted -= client_UploadCompleted;
canUpload = false;
}
else
{
canUpload = false;
}
client = null;
canUpload = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void client_GetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
try
{
List<System.Object> listItems = new List<object>();
if (e.Result != null)
{
listItems = e.Result["data"] as List<object>;
for (int x = 0; x < listItems.Count(); x++)
{
Dictionary<string, object> file1 = listItems[x] as Dictionary<string, object>;
string fileName = file1["name"].ToString();
if (fileName == lstmeasu[0].Title)
{
folderID = file1["id"].ToString();
folderAlredyPresent = true;
}
}
}
}
catch (Exception)
{
MessageBox.Show("An error occured in getting skydrive folders, please try again later.");
}
}
It miraculously works again without me changing any code. It seems to be resolved on the other end. I have no clue what was wrong.
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've created a simple tool that can find Sign up option in websites (200 website list is in arraylist).
I was using webbrowser but it has a problem of cache and cookie so i switched to webclient. It works fine when i put breakpoints and debug but when i run it normally, it also include those websites which doesn't have signup option.
Here is my code
private void btnSearch_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Start();
}
Timer1 code
string st;
private void timer1_Tick(object sender, EventArgs e)
{
st = "";
Application.DoEvents();
try
{
st = lst[dataindex2].ToString();
using (WebClient asyncWebRequest = new WebClient())
{
asyncWebRequest.DownloadDataCompleted += asyncWebRequest_DownloadDataCompleted;
Uri urlToRequest = new Uri(st);
asyncWebRequest.DownloadDataAsync(urlToRequest);
asyncWebRequest.Dispose();
}
dataindex2++;
if (dataindex2 == lst.Count)
{
timer1.Stop();
lblStatus.Text = "Stopped";
lblStatus.ForeColor = Color.DarkRed;
MessageBox.Show("Search Completed");
}
}
catch (Exception ex)
{
timer1.Stop();
lblStatus.Text = "Stopped";
lblStatus.ForeColor = Color.DarkRed;
timer1.Dispose();
MessageBox.Show(ex.Message);
return;
}
asyncWebRequest_DownloadDataCompleted code:
private void asyncWebRequest_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
if (e.Error != null)
{
timer1.Stop();
ena();
lblStatus.Text = "Stopped";
lblStatus.ForeColor = Color.DarkRed;
timer1.Dispose();
MessageBox.Show(e.Error.Message);
}
if (e.Result != null && e.Result.Length > 0)
{
string browsetext = "";
int = iSuccess = 0;
browsetext = Encoding.Default.GetString(e.Result);
iSuccess = browsetext.IndexOf("Sign up") + 1;
if (iSuccess == 0)
{
}
else
{
listBox1.Items.Add(st);
domaincount++;
lblDomainCount.ForeColor = Color.DarkGreen;
lblDomainCount.Text = domaincount.ToString();
}
}
else
{
}
}
}
else
{
MessageBox.Show("No data found.");
}
}
Please help and if there is any alternate of webclient that doesn't hang gui then please suggest. ty.
You dispose WebClient as soon as you start the download.
asyncWebRequest.DownloadDataAsync(urlToRequest);
asyncWebRequest.Dispose();
Please help and if there is any alternate of webclient that doesn't hang gui
see my other answer which creates a wrapper for WebClient to be able to use async/await. HttpClient can be an alternative too.
I am new 2 C# and I have been given a task... I have to write a C# code to download the sent email attachments and subject of email from Outlook 2007 to a local drive or any specified location. How do I do that? I am able to get the attachments which are in inbox. Can any one please help me getting the mails sent through Outlook?
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
this.Application.NewMail += new
Microsoft.Office.Interop.Outlook.
ApplicationEvents_11_NewMailEventHandler(ThisApplication_NewMail);
}
private void ThisApplication_NewMail()
{
Outlook.MAPIFolder SentMail = this.Application.ActiveExplorer().Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderSentMail);
Outlook.Items SentMailItems = SentMail.Items;
Outlook.MailItem newEmail = null;
//SentMailItems = SentMailItems.Restrict("[Unread] = true");
try
{
foreach (object collectionItem in SentMailItems)
{
newEmail = collectionItem as Outlook.MailItem;
if (newEmail != null)
{
if (newEmail.Attachments.Count > 0)
{
for (int i = 1; i <= newEmail.Attachments.Count; i++)
{
newEmail.Attachments[i].SaveAsFile(#"C:\TestFileSave\" + newEmail.Attachments[i].FileName);
}
}
}
}
}
catch (Exception ex)
{
string errorInfo = (string)ex.Message
.Substring(0, 11);
if (errorInfo == "Cannot save")
{
MessageBox.Show(#"Create Folder C:\TestFileSave");
}
}
}
Thanks in Advance
I've tested your code, the SaveAsFile() method of Attachment class instance throws:
{System.IO.DirectoryNotFoundException: Cannot save the attachment.
Path does not exist. Verify the path is correct. at
Microsoft.Office.Interop.Outlook.Attachment.SaveAsFile(String Path)
... }
So, it is necessary to make sure that the directory for saving attachments exists.
private void ThisApplication_NewMail()
{
const string destinationDirectory = #"C:\TestFileSave";
if (!Directory.Exists(destinationDirectory))
{
Directory.CreateDirectory(destinationDirectory);
}
MAPIFolder sentMail = Application.ActiveExplorer().Session.GetDefaultFolder(OlDefaultFolders.olFolderSentMail);
Items sentMailItems = sentMail.Items;
try
{
foreach (object collectionItem in sentMailItems)
{
MailItem newEmail = collectionItem as MailItem;
if (newEmail == null) continue;
if (newEmail.Attachments.Count > 0)
{
for (int i = 1; i <= newEmail.Attachments.Count; i++)
{
string filePath = Path.Combine(destinationDirectory, newEmail.Attachments[i].FileName);
newEmail.Attachments[i].SaveAsFile(filePath);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
Hope this helps.
Maintain a list which will store the sender's name then check a condition that the recent mail's sender contains in the list if yes than Download.
private void ThisApplication_NewMail()
{
const string destinationDirectory = #"C:\TestFileSave";
List<string> senderList = new List<string>();
if (!Directory.Exists(destinationDirectory))
{
Directory.CreateDirectory(destinationDirectory);
}
MAPIFolder sentMail = Application.ActiveExplorer().Session.GetDefaultFolder(OlDefaultFolders.olFolderSentMail);
Items sentMailItems = sentMail.Items;
try
{
foreach (object collectionItem in sentMailItems)
{
MailItem newEmail = collectionItem as MailItem;
senderEmailAdd = newEmail.SenderEmailAddress;
if (newEmail == null) continue;
if (newEmail.Attachments.Count > 0 && senderList.Contains(senderEmailAdd))
{
for (int i = 1; i <= newEmail.Attachments.Count; i++)
{
string filePath = Path.Combine(destinationDirectory, newEmail.Attachments[i].FileName);
newEmail.Attachments[i].SaveAsFile(filePath);
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}