How to send email from windows form app with log4net - winforms

I have set up log4net in my C# 3.5 windows form application. I am looking for how to send email from a client pc with log4net. The SMTPAppender requires knowledge of SMTPHost and the examples I've seen are for web applications.
Is there a way to send email from an application that will work on any client's computer that may or may not be in a domain or network. I guess I would also need to be able to check if there is a connection available.
I've searched for an answer but I don't have much experience programming with email or the web to know what to look for. Any ideas to steer me in the right direction?

c# SmtpClient is quite right for your needs. here's some sample code (host is an ip address or host name, and the port is usually 25, but not necessarily) :
public static void SendMail(
string host,
int port,
SmtpAuthentication authentication,
string userName,
string password,
string from,
string to,
string cc,
string subject,
string body,
string[] attachments)
{
// Create and configure the smtp client
SmtpClient smtpClient = new SmtpClient();
if (host != null && host.Length > 0)
{
smtpClient.Host = host;
}
smtpClient.Port = port;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
if (authentication == SmtpAuthentication.Basic)
{
// Perform basic authentication
smtpClient.Credentials = new System.Net.NetworkCredential(userName, password);
}
else if (authentication == SmtpAuthentication.Ntlm)
{
// Perform integrated authentication (NTLM)
smtpClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
}
MailMessage mailMessage = new MailMessage();
mailMessage.Body = body;
mailMessage.From = new MailAddress(from);
mailMessage.To.Add(to);
mailMessage.CC.Add(cc);
foreach (string attachement in attachments)
{
mailMessage.Attachments.Add(new Attachment(attachement));
}
mailMessage.Subject = subject;
mailMessage.Priority = MailPriority.Normal;
smtpClient.Send(mailMessage);
}
}

Related

Remotely update game content in Unity3d for WebGL [duplicate]

I am trying to connect to a MS SQL database through Unity. However, when I try to open a connection, I get an IOException: Connection lost.
I have imported System.Data.dll from Unity\Editor\Data\Mono\lib\mono\2.0. I am using the following code:
using UnityEngine;
using System.Collections;
using System.Data.Sql;
using System.Data.SqlClient;
public class SQL_Controller : MonoBehaviour {
string conString = "Server=myaddress.com,port;" +
"Database=databasename;" +
"User ID=username;" +
"Password=password;";
public string GetStringFromSQL()
{
LoadConfig();
string result = "";
SqlConnection connection = new SqlConnection(conString);
connection.Open();
Debug.Log(connection.State);
SqlCommand Command = connection.CreateCommand();
Command.CommandText = "select * from Artykuly2";
SqlDataReader ThisReader = Command.ExecuteReader();
while (ThisReader.Read())
{
result = ThisReader.GetString(0);
}
ThisReader.Close();
connection.Close();
return result;
}
}
This is the error I get:
IOException: Connection lost
Mono.Data.Tds.Protocol.TdsComm.GetPhysicalPacketHeader ()
Mono.Data.Tds.Protocol.TdsComm.GetPhysicalPacket ()
Mono.Data.Tds.Protocol.TdsComm.GetByte ()
Mono.Data.Tds.Protocol.Tds.ProcessSubPacket ()
Mono.Data.Tds.Protocol.Tds.NextResult ()
Mono.Data.Tds.Protocol.Tds.SkipToEnd ()
Rethrow as TdsInternalException: Server closed the connection.
Mono.Data.Tds.Protocol.Tds.SkipToEnd ()
Mono.Data.Tds.Protocol.Tds70.Connect (Mono.Data.Tds.Protocol.TdsConnectionParameters connectionParameters)
Mono.Data.Tds.Protocol.Tds80.Connect (Mono.Data.Tds.Protocol.TdsConnectionParameters connectionParameters)
Please disregard any security risks with this approach, I NEED to do this for testing, security will come later.
Thank you for your time.
Please disregard any security risks with this approach
Do not do it like this. It doesn't matter if security will come before or after. You will end of re-writing the whole code because the password is hard-coded in your application which can be decompiled and retrieved easily. Do the connection the correct way now so that you won't have to re-write the whole application.
Run your database command on your server with php, perl or whatever language you are comfortable with but this should be done on the server.
From Unity, use the WWW or UnityWebRequest class to communicate with that script and then, you will be able to send and receive information from Unity to the server. There are many examples out there. Even with this, you still need to implement your own security but this is much more better than what you have now.
You can also receive data multiple with json.
Below is a complete example from this Unity wiki. It shows how to interact with a database in Unity using php on the server side and Unity + C# on the client side.
Server Side:
Add score with PDO:
<?php
// Configuration
$hostname = 'localhot';
$username = 'yourusername';
$password = 'yourpassword';
$database = 'yourdatabase';
$secretKey = "mySecretKey"; // Change this value to match the value stored in the client javascript below
try {
$dbh = new PDO('mysql:host='. $hostname .';dbname='. $database, $username, $password);
} catch(PDOException $e) {
echo '<h1>An error has ocurred.</h1><pre>', $e->getMessage() ,'</pre>';
}
$realHash = md5($_GET['name'] . $_GET['score'] . $secretKey);
if($realHash == $hash) {
$sth = $dbh->prepare('INSERT INTO scores VALUES (null, :name, :score)');
try {
$sth->execute($_GET);
} catch(Exception $e) {
echo '<h1>An error has ocurred.</h1><pre>', $e->getMessage() ,'</pre>';
}
}
?>
Retrieve score with PDO:
<?php
// Configuration
$hostname = 'localhost';
$username = 'yourusername';
$password = 'yourpassword';
$database = 'yourdatabase';
try {
$dbh = new PDO('mysql:host='. $hostname .';dbname='. $database, $username, $password);
} catch(PDOException $e) {
echo '<h1>An error has occurred.</h1><pre>', $e->getMessage() ,'</pre>';
}
$sth = $dbh->query('SELECT * FROM scores ORDER BY score DESC LIMIT 5');
$sth->setFetchMode(PDO::FETCH_ASSOC);
$result = $sth->fetchAll();
if(count($result) > 0) {
foreach($result as $r) {
echo $r['name'], "\t", $r['score'], "\n";
}
}
?>
Enable cross domain policy on the server:
This file should be named "crossdomain.xml" and placed in the root of your web server. Unity requires that websites you want to access via a WWW Request have a cross domain policy.
<?xml version="1.0"?>
<cross-domain-policy>
<allow-access-from domain="*"/>
</cross-domain-policy>
Client/Unity Side:
The client code from Unity connects to the server, interacts with PDO and adds or retrieves score depending on which function is called. This client code is slightly modified to compile with the latest Unity version.
private string secretKey = "mySecretKey"; // Edit this value and make sure it's the same as the one stored on the server
public string addScoreURL = "http://localhost/unity_test/addscore.php?"; //be sure to add a ? to your url
public string highscoreURL = "http://localhost/unity_test/display.php";
//Text to display the result on
public Text statusText;
void Start()
{
StartCoroutine(GetScores());
}
// remember to use StartCoroutine when calling this function!
IEnumerator PostScores(string name, int score)
{
//This connects to a server side php script that will add the name and score to a MySQL DB.
// Supply it with a string representing the players name and the players score.
string hash = Md5Sum(name + score + secretKey);
string post_url = addScoreURL + "name=" + WWW.EscapeURL(name) + "&score=" + score + "&hash=" + hash;
// Post the URL to the site and create a download object to get the result.
WWW hs_post = new WWW(post_url);
yield return hs_post; // Wait until the download is done
if (hs_post.error != null)
{
print("There was an error posting the high score: " + hs_post.error);
}
}
// Get the scores from the MySQL DB to display in a GUIText.
// remember to use StartCoroutine when calling this function!
IEnumerator GetScores()
{
statusText.text = "Loading Scores";
WWW hs_get = new WWW(highscoreURL);
yield return hs_get;
if (hs_get.error != null)
{
print("There was an error getting the high score: " + hs_get.error);
}
else
{
statusText.text = hs_get.text; // this is a GUIText that will display the scores in game.
}
}
public string Md5Sum(string strToEncrypt)
{
System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
byte[] bytes = ue.GetBytes(strToEncrypt);
// encrypt bytes
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] hashBytes = md5.ComputeHash(bytes);
// Convert the encrypted bytes back to a string (base 16)
string hashString = "";
for (int i = 0; i < hashBytes.Length; i++)
{
hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
}
return hashString.PadLeft(32, '0');
}
This is just an example on how to properly do this. If you need to implement session feature and care about security, look into the OAuth 2.0 protocol. There should be existing libraries that will help get started with the OAuth protocol.
An alternative would be to create your own dedicated server in a command prompt to do your communication and connecting it to unity to Handel multiplayer and SQL communication. This way you can stick with it all being created in one language. But a pretty steep learning curve.
Unity is game engine.
so That's right what the answer says.
but, Some domains need to connect database directly.
You shouldn't do that access database directly in game domain.
Anyway, The problem is caused by NON-ENGLISH computer name.
I faced sort of following errors at before project.
IOException: Connection lost
Mono.Data.Tds.Protocol.TdsComm.GetPhysicalPacketHeader ()
Mono.Data.Tds.Protocol.TdsComm.GetPhysicalPacket ()
Mono.Data.Tds.Protocol.TdsComm.GetByte ()
Mono.Data.Tds.Protocol.Tds.ProcessSubPacket ()
Mono.Data.Tds.Protocol.Tds.NextResult ()
Mono.Data.Tds.Protocol.Tds.SkipToEnd ()
Rethrow as TdsInternalException: Server closed the connection.
Mono.Data.Tds.Protocol.Tds.SkipToEnd ()
Mono.Data.Tds.Protocol.Tds70.Connect (Mono.Data.Tds.Protocol.TdsConnectionParameters connectionParameters)
Mono.Data.Tds.Protocol.Tds80.Connect (Mono.Data.Tds.Protocol.TdsConnectionParameters connectionParameters)
And after changing computer name as ENGLISH, It works.
I don't know how it's going. But It works.
Mono's System.Data.dll has some issues in P.C has NON-ENGLISH Computer name.
So, at least Unity project.
You should tell your customer Do not set their computer name as NON-ENGLISH.
I don't know people in mono knows these issue or not.
---------- It's OK in after 2018 version ----------
Api Compatibility Level > .Net 4.x
You can connect database in Non-english computer name machine.

How do i manage the SQL Server connections in asp.net core MVC mode?

I am working on a APP's server program which using asp.net core MVC mode. And in the XXXXcontrller i never use code like "Connection.open()" and "Connection.close()",a HTTP GET action is like this.
public async Task<IActionResult> register(string phoneNum, string password, string userType)
{
//从数据库里找到m.Id和 id相同的车,赋给dbCars
var dbCars = await _context.dbUsers.SingleOrDefaultAsync(m => m.UserName == phoneNum);
// var dbCars= _context.dbCars.Where(s => s.Id == id).FirstOrDefault<dbCars>();
if (dbCars == null)//如果为空,则注册
{
//注册新用户
dbCars = new dbUsers();
dbCars.UserName = phoneNum;
dbCars.Password = password;
dbCars.UserType = userType;
dbCars.IsVerified = true;
_context.Add(dbCars);
await _context.SaveChangesAsync();
//注册完成之后,把ID、用户类型和是否认证返回回去
List<string> userInfo = new List<string>();
userInfo.Add(dbCars.Id.ToString().Trim());
userInfo.Add(dbCars.UserType.ToString().Trim());
userInfo.Add(dbCars.IsVerified.ToString());
string json = JsonConvert.SerializeObject(userInfo);
return Ok(json);
}
else //如果不为空就代表注册过了
{
return Ok("0"); //返回1代表注册过了
}
}
I wondered how should i maintain the SQL Connections when many users access this service?? Should I close these connections manually? Or it can be done automatically by some magic?? If many users access this service, do my program breaked down??
I am confused, who can give me an answer??
if you are using Entity Framework or ORM you should see and set the connection string on the web.config or if it's on a separate layer you can see the settings on the app.config. If you run the application it will use the startup project of your application connectionstring app.config(windows application) or web.config (web application)

SSIS Send email from package that is off the domain

I have a SSIS package that is deployed to server that is not on a domain but it is within our network perimeter. I would like to be able to send an email on package failure but being off the domain presents a challenge that I have not faced before.
Using a dummy gmail account is not acceptable to the business.
I would like to use the company SMTP server (mail.somecompany.com) but I do not know how to do this while off the domain. Can someone please tell me if this is possible and what steps I need to take.
Useful information:
SQL Server 2016
Project Deployment mode
Visual Studio 2015
Many thanks in advance.
You can use script task for sending mail.
This might can help you:
MailMessage Mymsg = new MailMessage();
SmtpClient smptserver = new SmtpClient();
System.Net.Mail.Attachment attach;
Mymsg.From = new MailAddress("aa#abc.com");
String Tolist = Convert.ToString("a#aa.com");
String CClist = Convert.ToString("a#xse.com");
String BCClist = Convert.ToString("ba#aas.com");
if (!String.IsNullOrEmpty(Tolist))
Mymsg.To.Add(Tolist);
if (!String.IsNullOrEmpty(CClist))
Mymsg.CC.Add(CClist);
if (!String.IsNullOrEmpty(BCClist))
Mymsg.Bcc.Add(BCClist);
Mymsg.Subject = "Subject!";
Mymsg.Body = "Hi, Your message!";
Mymsg.IsBodyHtml = true;
try
{
smptserver.Send(Mymsg);
Console.WriteLine("OK");
}
catch (System.Net.Mail.SmtpException ex)
{
Console.WriteLine(ex.StatusCode.ToString());
}
Dts.TaskResult = (int)ScriptResults.Success;
smptserver = null;
Mymsg = null;

SMTP Connection for SSIS 2008

I am new to SSIS and trying to figure out a way to set up a SMTP connection for an email. I did some online research about this but didn't find a clear explanation on how set up a smtp connection. Can I use outlook 2013 to send an email from SSIS? If yes then how do I create a new smtp connection using outlook 2013
I am trying to send an email from ssis with the ID like donotreply#abc.com
Here i used System.Net.Mail assembly to send email notification.
Add a script task in your SSIS package and include this code provided that your smtp server is working.
private void SendMail(
string sendTo,
string from,
string subject,
string body,
bool isBodyHtml,
string SMTPServer,
string userName,
string password,
string domain,
string attachments,
string sendCC)
{
System.Net.Mail.MailMessage oMessage = default(System.Net.Mail.MailMessage);
System.Net.Mail.SmtpClient mySmtpClient = default(System.Net.Mail.SmtpClient);
oMessage = new System.Net.Mail.MailMessage(from, sendTo, subject, body);
oMessage.CC.Add(sendCC);
oMessage.IsBodyHtml = isBodyHtml;
mySmtpClient = new System.Net.Mail.SmtpClient(SMTPServer, 25);
if (string.IsNullOrEmpty(userName))
{
mySmtpClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
}
else
{
mySmtpClient.Credentials = new System.Net.NetworkCredential(userName, password, domain);
}
mySmtpClient.Send(oMessage);
}

Exception occurred while reading mails from exchange server 2010 using imap

I am trying to read the mails from the exchange server 2010 , however sometimes the connection got established , but remaining times program gives below exception:
javax.mail.AuthenticationFailedException: LOGIN failed
The code is working fine with the exchange server 2007 . But from the time mailbox has been migrated to 2010, the program is behaving in this fashion only.
I have also tried with several options available on net, but nothing is working. I am using javamail-1.4.4 API version . Here is the piece of code through which I am just trying to connect to the mailbox .
public class ReadMail {
static Store store=null;
static String host="";
static String username="";
static String password="";
public static void main(String[] arg) throws Exception{
try{
Session session;
username = "username";
password = "password";
host = "hostname";
Properties props = System.getProperties();
props.setProperty("mail.smtp.auth","true");
session = Session.getInstance(props,
new ExchangeAuthenticator(username, password));
Store st = session.getStore("imaps");
st.connect(host,username, password);
System.out.println("Connected");
}
catch (Exception e){
e.printStackTrace(System.out);
}
}
}
public class ExchangeAuthenticator extends Authenticator {
String user;
String pw;
public ExchangeAuthenticator (String username, String password)
{
super();
this.user = username;
this.pw = password;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, pw);
}
}
I also face same problem in my code i set two properties in my code
disable plain test and enable NTLM
props.setProperty("mail.imap.auth.plain.disable","true");
props.setProperty("mail.imap.starttls.enable", "true");
now my code able to connect with exchange server
read it
https://forums.oracle.com/forums/thread.jspa?threadID=1587688
Perhaps the configuration of the server has changed and it's no longer accepting your credentials, or no longer supporting any of the login methods that JavaMail supports.
Turn on session debugging and examine the protocol trace. It should provide some clues as to why it's failing.
You might also want to upgrade to JavaMail 1.4.5, which has built-in support for NTLM authentication, which you might need.
Even though your credentials are OK, the new server might not accept your login method. For instance, the new server might not allow "Plain" authentication.
The debugging info should show which authentication methods are accepted.

Resources