I have recently purchased a new computer, and now my e-mails never get sent, and there are NEVER any exceptions thrown or anything.
Can somebody please provide some samples that work using the SmtpClient class? Any help at all will be greatly appreciated.
Thank you
Updates
Ok - I have added credentials now. And can SUCCESSFULLY SEND e-mail synchronously. But I can still not send them asynchronously.
Old:
After trying to send e-mail synchronously, I receive the following exception:
Transaction failed. The server response was:
5.7.1 <myfriend#hotmails.com>: Relay access denied.
You can send mail through Async(). How means you should follow the below code,
smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
smtpClient.SendAsync(mailMessage, mailMessage);
and, if you are using async, you need to also have the event handler like,
static void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
//to be implemented
}
By using this, you can send Mail.
You could first try the synchronous Send method to verify that everything is setup correctly with the SMTP server and that you don't get any exceptions:
var client = new SmtpClient("smtp.somehost.com");
var message = new MailMessage();
message.From = new MailAddress("from#somehost.com");
message.To.Add(new MailAddress("to#somehost.com"));
message.Subject = "test";
message.Body = "test body";
client.Send(message);
Remark: In .NET 4 SmtpClient implements IDisposable so make sure you wrap it in a using statement.
Related
I want to send a simple message using the service Clickatell.
I don't want to read the response, it will be simple GET request to send a message.
The service provides the request looks like:
https://platform.clickatell.com/messages/http/send?apiKey=xxxxxxxxxxxxxxxx==&to=xxxxxxxxxxx&content=Test+message+text
I checked it with curl
curl "https://platform.clickatell.com/messages/http/send?apiKey=apiKEY==&to=NUMBER&content=Test+message+text"
and it's working really fine.
I try to use it with my Windows Forms application with HTTP request
Below is the code which I provided:
var client2 = new HttpClient();
client2.GetAsync("https://platform.clickatell.com/messages/http/send?apiKey=apiKEY==&to=NUMBER&content=Test+message+text");
App.Write("SMS SEND!");
I have info that SMS send, but I didn't receive it. My friend use my code in the .NET application and it's working for him.
Do I miss something?
Maybe it's really worth to mention I need to add to References manually using System.Net.Http;
EDIT:
I tried to add to do it async, so I edit my code to:
static void sendSMS()
{
var client2 = new HttpClient();
var task = client2.GetAsync("https://platform.clickatell.com/messages/http/send?apiKey=API_KEY==&to=MY_NUMBER&content=Test+message+text");
task.Wait();
App.Write("SMS SEND!");
}
But now the SMS SEND message in the application is not shown.
Ok I know You use .NET 4.5 and You probably have problem with a exeption
"The underlying connection was closed: An unexpected error occurred on a send"
The right code it looks like this: (You must add 'SecurityProtocol 'before reqeust):
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
var client2 = new HttpClient();
client2.GetAsync("https://platform.clickatell.com/messages/http/send?apiKey=apiKEY==&to=NUMBER&content=Test+message+text").Result;
More details herehttps://stackoverflow.com/a/32789483/5816153
my code is :
Pop3Client client = new Pop3Client();
client.Connect("pop.gmail.com", 995, true);
client.Authenticate("MyMailAccont#gmail.com", "Password");
....
error on Authenticate.eeror is:
Additional information: POP3 server did not respond with a +OK
response to the AUTH command.
my config is well.how to fix it?
gmail not work very well with pop3.
I can't find an example of sending message by telegram protocol from C#. I tried to use this but failed.
Can you give me any examples?
TLSharp is basic implementation of Telegram API on C#. See it here https://github.com/sochix/TLSharp
You can use the WTelegramClient library to connect to Telegram Client API protocol (as a user, not a bot)
The library is very complete but also very easy to use. Follow the README on GitHub for an easy introduction.
To send a message to someone can be as simple as:
using TL;
using var client = new WTelegram.Client(); // or Client(Environment.GetEnvironmentVariable)
await client.LoginUserIfNeeded();
var result = await client.Contacts_ResolveUsername("USERNAME");
await client.SendMessageAsync(result.User, "Hello");
//or by phone number:
//var result = await client.Contacts_ImportContacts(new[] { new InputPhoneContact { phone = "+PHONENUMBER" } });
//client.SendMessageAsync(result.users[result.imported[0].user_id], "Hello");
For my bot I use Telegram.Bot nuget package. Full sample code is here.
Here is example of sending message in reply to incoming message.
// create bot instance
var bot = new TelegramBotClient("YourApiToken");
// test your api configured correctly
var me = await bot.GetMeAsync();
Console.WriteLine($"{me.Username} started");
// start listening for incoming messages
while (true)
{
//get incoming messages
var updates = await bot.GetUpdatesAsync(offset);
foreach (var update in updates)
{
// send response to incoming message
await bot.SendTextMessageAsync(message.Chat.Id,"The Matrix has you...");
}
}
The simplest way is to send http request directly to the Telegram BOT API as url string, you may test those url strings even in your browser, please see details in my another answer here:
https://stackoverflow.com/a/57341990/11687179
at the first step you have to generate a bot in botfather then use the code in bellow in C#
private void SendMessage(string msg)
{
string url = "https://api.telegram.org/{botid}:{botkey}/sendMessage?chat_id={#ChanalName}&text={0}";
WebClient Client = new WebClient();
/// If you need to use proxy
if (Program.UseProxy)
{
/// proxy elements are variable in Program.cs
Client.Proxy = new WebProxy(Program.ProxyUrl, Program.ProxyPort);
Client.Proxy.Credentials = new NetworkCredential("hjolany", "klojorasic");
}
Client.DownloadString(string.Format(url, msg));
}));
}
Telegram has an official API that can do exactly what you need, you will have to look into http requests though..
Here is the documentation on sending a message:
Function
messages.sendMessage
Params
peer InputPeer User or chat where a message will be sent
message string Message text
random_id long Unique client message ID required to prevent message resending
Query example
(messages.sendMessage (inputPeerSelf) "Hello, me!" 12345678901)
Return errors
Code Type Description
400 BAD_REQUEST PEER_ID_INVALID Invalid peer
400 BAD_REQUEST MESSAGE_EMPTY Empty or invalid UTF8 message was sent
400 BAD_REQUEST MESSAGE_TOO_LONG Message was too long.
Current maximum length is 4096 UTF8 characters
For the full documentation go here.
I'm trying to convert some Python code for use in a .Net website. The code retrieves a message stored in RFC822 format and sends the message to an SMTP server again using:
mail from: blah blah
rcpt to: blah blah
data
<send the text from the RFC822 file here>
.
So no parsing of the RFC822 file is required (fortunately!). In Python this is simply:
smtp = smtplib.SMTP(_SMTPSERVER)
smtp.sendmail(_FROMADDR, recipient, msg)
where the file has been read into the variable msg. Is there an easy way to do this in C#?
The built in C# SMTP objects don't offer a way to do this, or at least I haven't found a way. They seem to be based on the principle of building up a MailMessage by providing the addresses, subject and body separately. SmtpClient has a Send(string, string, string, string) method, but again this requires a separate subject and body so I guess it constructs the RFC822 formatted message for you.
If necessary I can write my own class to send the mail. It's such a simple requirement that it wouldn't take long. However if there is a way using the standard libraries they're probably less buggy than my code.
I would recommend using MimeKit to parse the message file and then use MailKit to send via SMTP. MailKit is based on MimeKit, so they work well together and MailKit's SmtpClient is superior to System.Net.Mail's implementation.
Parsing a message is as simple as this:
var message = MimeMessage.Load (fileName);
Sending the message is as simple as these few lines:
using (var client = new SmtpClient ()) {
client.Connect ("smtp.gmail.com", 465, true);
client.Authenticate ("username", "password");
client.Send (message);
client.Disconnect (true);
}
You're right, the inbuilt stuff doesn't offer a solution for this.
My advice would be to simply write a bit of code that uses TcpClient and StreamReader / StreamWriter to interact with the SMTP server. It shouldn't need more than 50 lines of code.
This is easy to do, you need only to install MailKit and MimeKit from nuget.
Pay attention because if you don't need authentication, setting "useSsl" to false is not enough, it doesn't work. You need to set MailKit.Security.SecureSocketOptions.None
var message = MimeMessage.Load("pathToEml");
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
client.Connect("smtp.yourserver.yourdomain", 25, MailKit.Security.SecureSocketOptions.None); //set last param to true for authentication
//client.Authenticate("username", "password");
client.Send(message);
client.Disconnect(true);
}
I have a tiny app that I wanting to run and ping an internal web site. Here is the code:
using (var client = new WebClient())
{
client.DownloadString("http://MyServer/dev/MyApp");
}
However, it is throwing the following error:
The remote server returned an error: (401) Unauthorized.
I have all the correct credentials to access the server. I am thinking I don't know how to use WebClient very well and I just need to set properties on the client object. Any ideas?
I found the answer. I needed to use the NetworkCredentials() method of WebClient. See below:
using (var client = new WebClient())
{
client.Credentials = new NetworkCredential ("theUser", "thePassword", "theDomain");
client.DownloadString("http://MyServer/dev/MyApp");
}
This is the URL that helped me