How to handle alarms by taking a snapshot and sending it as an e-mail in C#

This example demonstrates in a really simple manner how to take a snapshot and send it as an e-mail in C# when motion has been detected by the camera device. To implement this example, you must have Ozeki Camera SDK installed, and a reference to OzekiSDK.dll should be added to your Visual Studio project.

How to handle alarms by taking a snapshot and sending it as an e-mail using C#?

To establish the connection properly between your application and an IP camera you should apply the same code snippet what you have used in the example (How to connect to an IP camera device using C#?). Important: you should study this article in order to find out how to setup your Windows Forms/WPF Application correctly. It's also recommended to visit the How to setup viewer side motion detection and How to take a picture snapshot article before you begin to study and use this functionality.

Getting started

To get started it is recomended to Download and Install the latest version of Ozeki Camera SDK. After installation you can find the example code discussed in this page with full source code in the following location on your harddisk:

Download Ozeki Camera SDK: https://camera-sdk.com/p_6513-download-onvif-ozeki-camera-sdk-for-c-sharp.html
Windows forms version: C:\Program Files\Ozeki\Ozeki SDK\examples.zip\Examples\Other\
Motion_Detection_Snapshot_Email_WF\Motion_Detection_Snapshot_Email_WF.sln
WPF version: C:\Program Files\Ozeki\Ozeki SDK\examples.zip\Examples\Other\
Motion_Detection_Snapshot_Email_WPF\Motion_Detection_Snapshot_Email_WPF.sln

To compile this example you will need Microsoft Visual Studio installed on your computer.

The additional statements and methods of this example are the following:
first you need a new class member that is going to represent the image file we can use when a snapshot has been taken.

private Image _image;
	

You have to subscribe for the events of the motion detector:

_motionDetector.MotionDetection += _motionDetector_MotionDetection;
	

When the event occurs the application is going to indicate it on one of the GUI's labels:

label_Motion.Text = "Motion detected";
	

We handle the true value by taking a snapshot within a new task then saving the image with the actual date. Finally, we are going to call the SendEmail() method:

var date = DateTime.Now.Year + "y-" + DateTime.Now.Month + "m-" + DateTime.Now.Day + "d-" +
			DateTime.Now.Hour + "h-" + DateTime.Now.Minute + "m-" + DateTime.Now.Second + "s";
var filename = "Camera_" + date + ".jpg";

Task.Factory.StartNew(() =>
{
    var snapshot = _snapshot.TakeSnapshot();
    _image = snapshot.ToImage();
    _image.Save(filename);
    SendEmail(filename);
});
	

The .NET Framework supports the e-mail sending functionality so you can use the System.Net.Mail class for this purpose. In the SendEmail() method you have to use existing sender e-mail address with its password, and an existing receiver e-mail address. We can set the subject, body and attachment properties and the SMTP client as well. In this example we use smtp.gmail.com as a host. Finally, the smtp.send() method will send the e-mail.

Taking a snapshot picture and sending it as an e-mail in C#

Windows Form WPF  

Windows forms version

Form1.cs

	using System;
	using System.Drawing;
	using System.IO;
	using System.Net;
	using System.Net.Mail;
	using System.Net.Mime;
	using System.Windows.Forms;
	using System.Threading.Tasks;
	using Ozeki.Media;
	using Ozeki.Camera;
	
	namespace OnvifIPCameraMotionDetection06
	{
    public partial class Form1 : Form
    {
        private IIPCamera _camera;
        private DrawingImageProvider _imageProvider;
        private MediaConnector _connector;
        private VideoViewerWF _videoViewerWf;
        private MotionDetector _motionDetector;
        private Image _image;
        private SnapshotHandler _snapshot;

        public Form1()
        {
            InitializeComponent();
            _imageProvider = new DrawingImageProvider();
            _connector = new MediaConnector();
            _snapshot = new SnapshotHandler();
            _motionDetector = new MotionDetector();
            _motionDetector.MotionDetection += _motionDetector_MotionDetection;
            _motionDetector.MotionColor = MotionColor.Red;
            _motionDetector.HighlightMotion = HighlightMotion.Highlight;
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            _videoViewerWf = new VideoViewerWF
            {
                Size = new Size(260, 180),
                BackColor = Color.Black,
                TabStop = false,
                FlipMode = FlipMode.None,
                Location = new Point(40, 30),
                Name = "_videoViewerWf"
            };
            CameraBox.Controls.Add(_videoViewerWf);
        }

        // If motion has been detected we are going to create a snapshot using the actual date in its name and call the SendEmail() method
        private void _motionDetector_MotionDetection(object sender, MotionDetectionEvent e)
        {
            if (e.Detection)
            {
                InvokeGuiThread(() => label_Motion.Text = "Motion detected");

                var date = DateTime.Now.Year + "y-" + DateTime.Now.Month + "m-" + DateTime.Now.Day + "d-" +
                                DateTime.Now.Hour + "h-" + DateTime.Now.Minute + "m-" + DateTime.Now.Second + "s";
                var filename = "Camera_" + date + ".jpg";

                Task.Factory.StartNew(() =>
                {
                    var snapshot = _snapshot.TakeSnapshot();
                    _image = snapshot.ToImage();
                    _image.Save(filename);
                    SendEmail(filename);
                });
            }
            else
                InvokeGuiThread(() => label_Motion.Text = "Motion ended");
        }

        private void SendEmail(string file)
        {
            try
            {
                var fromAddress = new MailAddress("from@gmail.com", "OZEKI");
                var toAddress = new MailAddress("to@gmail.com", "OZEKI");
                const string fromPassword = "myPassowrd";
                const string subject = "Alarm Snapshot";
                const string body = "Motion detected";

                var attachmentFilename = file;
                var attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);
                if (attachmentFilename != null)
                {
                    ContentDisposition disposition = attachment.ContentDisposition;
                    disposition.CreationDate = File.GetCreationTime(attachmentFilename);
                    disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
                    disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
                    disposition.FileName = Path.GetFileName(attachmentFilename);
                    disposition.Size = new FileInfo(attachmentFilename).Length;
                    disposition.DispositionType = DispositionTypeNames.Attachment;
                }

                var smtp = new SmtpClient
                {
                    Host = "smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
                };
                using (var message = new MailMessage(fromAddress, toAddress)
                {
                    Subject = subject,
                    Body = body
                })
                {
                    message.Attachments.Add(attachment);
                    smtp.Send(message);
                    InvokeGuiThread(() => label_Email.Text = "Sending successful");
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show("Error: " + exception.Message);
            }
        }

        private void button_Connect_Click(object sender, EventArgs e)
        {
            _camera = IPCameraFactory.GetCamera("192.168.115.175:8080", "admin", "admin");

            _connector.Connect(_camera.VideoChannel, _motionDetector);
            _connector.Connect(_motionDetector, _imageProvider);
            _connector.Connect(_camera.VideoChannel, _snapshot);
            _videoViewerWf.SetImageProvider(_imageProvider);
            _videoViewerWf.Start();
            _camera.Start();
            _motionDetector.Start();
        }

        private void InvokeGuiThread(Action action)
        {
            BeginInvoke(action);
        }
    }
	}
		
Code 1 - Taking a snapshot picture and sending it as an e-mail in C#

Please note that none of the cancel and disconnect methods are included in the example because of the demonstrating intent and briefness of the article.

GUI

how to handle alarms by taking a snapshot picture and sending it as email
Figure 1 - The graphical user interface of your application

After the successful implementation of the functions and the GUI elements, the application will work properly. Pressing the connect button will load in the image of the IP camera device connected to your PC into the panel that you can see on the picture. When the motion detector detects motion, the motion label's text will be true. After the e-mail was successfully sent the email label's text will indicate it.

Below you can find the code that belongs to the interface of the previously presented application. With the help of this section your Windows Forms Application will be able to work properly.

Form1.Designer.cs

	namespace OnvifIPCameraMotionDetection06
	{
    partial class Form1
    {
        private System.ComponentModel.IContainer components = null;

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        private void InitializeComponent()
        {
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.button_Connect = new System.Windows.Forms.Button();
            this.CameraBox = new System.Windows.Forms.GroupBox();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.label_Email = new System.Windows.Forms.Label();
            this.label_Motion = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.SuspendLayout();
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.button_Connect);
            this.groupBox1.Location = new System.Drawing.Point(10, 10);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(110, 70);
            this.groupBox1.TabIndex = 0;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "Connect";
            // 
            // button_Connect
            // 
            this.button_Connect.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.5F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238)));
            this.button_Connect.ForeColor = System.Drawing.Color.Black;
            this.button_Connect.Location = new System.Drawing.Point(15, 25);
            this.button_Connect.Name = "button_Connect";
            this.button_Connect.Size = new System.Drawing.Size(80, 23);
            this.button_Connect.TabIndex = 6;
            this.button_Connect.Text = "Connect";
            this.button_Connect.UseVisualStyleBackColor = true;
            this.button_Connect.Click += new System.EventHandler(this.button_Connect_Click);
            // 
            // CameraBox
            // 
            this.CameraBox.Location = new System.Drawing.Point(10, 85);
            this.CameraBox.Name = "CameraBox";
            this.CameraBox.Size = new System.Drawing.Size(345, 230);
            this.CameraBox.TabIndex = 3;
            this.CameraBox.TabStop = false;
            this.CameraBox.Text = "Live camera ";
            // 
            // groupBox2
            // 
            this.groupBox2.Controls.Add(this.label_Email);
            this.groupBox2.Controls.Add(this.label_Motion);
            this.groupBox2.Controls.Add(this.label2);
            this.groupBox2.Controls.Add(this.label1);
            this.groupBox2.Location = new System.Drawing.Point(145, 10);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(210, 70);
            this.groupBox2.TabIndex = 4;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "Motion alarm";
            // 
            // label_Email
            // 
            this.label_Email.AutoSize = true;
            this.label_Email.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.label_Email.Location = new System.Drawing.Point(105, 45);
            this.label_Email.Name = "label_Email";
            this.label_Email.Size = new System.Drawing.Size(2, 15);
            this.label_Email.TabIndex = 3;
            // 
            // label_Motion
            // 
            this.label_Motion.AutoSize = true;
            this.label_Motion.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.label_Motion.Location = new System.Drawing.Point(105, 20);
            this.label_Motion.Name = "label_Motion";
            this.label_Motion.Size = new System.Drawing.Size(2, 15);
            this.label_Motion.TabIndex = 2;
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(10, 45);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(78, 13);
            this.label2.TabIndex = 1;
            this.label2.Text = "E-mail sending:";
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(10, 20);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(42, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "Motion:";
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(374, 324);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.CameraBox);
            this.Controls.Add(this.groupBox1);
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.Name = "Form1";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "Onvif Camera Motion Detection Emailing Snapshot";
            this.Load += new System.EventHandler(this.MainForm_Load);
            this.groupBox1.ResumeLayout(false);
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            this.ResumeLayout(false);

        }

        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.Button button_Connect;
        private System.Windows.Forms.GroupBox CameraBox;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.Label label_Email;
        private System.Windows.Forms.Label label_Motion;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label1;
    }
	}
		
Code 2 - GUI example in C#

WPF version

MainWindow.xaml.cs

using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Threading.Tasks;
using System.Windows;
using Ozeki.Media;
using Ozeki.Camera;

namespace OnvifIPCameraMotionDetection06Wpf
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        private IIPCamera _camera;
        private DrawingImageProvider _drawingImageProvider;
        private MediaConnector _connector;
        private MotionDetector _motionDetector;
        private SnapshotHandler _snapshot;
        private Image _image;

        public MainWindow()
        {
            InitializeComponent();

            _drawingImageProvider = new DrawingImageProvider();
            _connector = new MediaConnector();
            _snapshot = new SnapshotHandler();
            _motionDetector = new MotionDetector();
            _motionDetector.MotionDetection += _motionDetector_MotionDetection;
            videoViewer.SetImageProvider(_drawingImageProvider);
        }

        private void Connect_Click(object sender, RoutedEventArgs e)
        {
            _camera = new IPCamera("192.168.112.109:8080", "user", "qwe123");

            _connector.Connect(_camera.VideoChannel, _motionDetector);
            _connector.Connect(_motionDetector, _drawingImageProvider);
            _connector.Connect(_camera.VideoChannel, _snapshot);
            videoViewer.Start();
            _camera.Start();
            _motionDetector.Start();
        }

        // If motion has been detected we are going to create a snapshot using the actual date in its name and call the SendEmail() method
        private void _motionDetector_MotionDetection(object sender, MotionDetectionEvent e)
        {
            if (e.Detection)
            {
                InvokeGuiThread(() => label_Motion.Content = "Motion detected");

                var date = DateTime.Now.Year + "y-" + DateTime.Now.Month + "m-" + DateTime.Now.Day + "d-" +
                                DateTime.Now.Hour + "h-" + DateTime.Now.Minute + "m-" + DateTime.Now.Second + "s";
                var filename = "Camera_" + date + ".jpg";

                Task.Factory.StartNew(() =>
                {
                    _image = _snapshot.TakeSnapshot().ToImage();
                    _image.Save(filename);
                    SendEmail(filename);
                });
            }
            else
                InvokeGuiThread(() => label_Motion.Content = "Motion ended");
        }

        private void SendEmail(string file)
        {
            try
            {
                var fromAddress = new MailAddress("from@gmail.com", "OZEKI");
                var toAddress = new MailAddress("to@gmail.com", "OZEKI");
                const string fromPassword = "myPassword";
                const string subject = "Alarm Snapshot";
                const string body = "Motion detected";

                var attachmentFilename = file;
                var attachment = new Attachment(attachmentFilename, MediaTypeNames.Application.Octet);
                if (attachmentFilename != null)
                {
                    ContentDisposition disposition = attachment.ContentDisposition;
                    disposition.CreationDate = File.GetCreationTime(attachmentFilename);
                    disposition.ModificationDate = File.GetLastWriteTime(attachmentFilename);
                    disposition.ReadDate = File.GetLastAccessTime(attachmentFilename);
                    disposition.FileName = Path.GetFileName(attachmentFilename);
                    disposition.Size = new FileInfo(attachmentFilename).Length;
                    disposition.DispositionType = DispositionTypeNames.Attachment;
                }

                var smtp = new SmtpClient
                {
                    Host = "smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
                };
                using (var message = new MailMessage(fromAddress, toAddress)
                {
                    Subject = subject,
                    Body = body
                })
                {
                    message.Attachments.Add(attachment);
                    smtp.Send(message);
                    InvokeGuiThread(() => label_Email.Content = "Sending successful");
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show("Error: " + exception.Message);
            }
        }

        private void InvokeGuiThread(Action action)
        {
            Dispatcher.BeginInvoke(action);
        }
    }
}
		
Code 1 - Taking a snapshot picture and sending it as an e-mail in C#

Please note that none of the cancel and disconnect methods are included in the example because of the demonstrating intent and briefness of the article.

GUI

how to handle alarms by taking a snapshot picture and sending it as email
Figure 1 - The graphical user interface of your application

After the successful implementation of the functions and the GUI elements, the application will work properly. Pressing the connect button will load in the image of the IP camera device connected to your PC into the panel that you can see on the picture. When the motion detector detects motion, the motion label's text will be true. After the e-mail was successfully sent the email label's text will indicate it.

Below you can find the code that belongs to the interface of the previously presented application. With the help of this section your WPF Application will be able to work properly.

MainWindow.xaml

<Window x:Class="OnvifIPCameraMotionDetection06Wpf.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:controls="clr-namespace:Ozeki.Media;assembly=OzekiSDK"
    Title="Motion detection snapshot" Height="382" Width="336" ResizeMode="CanMinimize" WindowStartupLocation="CenterScreen">
<Grid>
    <GroupBox Header="Live camera" HorizontalAlignment="Left" Margin="12,113,0,0" VerticalAlignment="Top" Height="226" Width="308">
        <Grid HorizontalAlignment="Left" Height="204" VerticalAlignment="Top" Width="296">
            <controls:VideoViewerWPF Name="videoViewer" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Background="Black"/>
        </Grid>
    </GroupBox>
    <Button Content="Connect" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="75" RenderTransformOrigin="-0.107,-0.364" Click="Connect_Click"/>
    <GroupBox Header="Motion alarm" HorizontalAlignment="Left" Margin="127,12,0,0" VerticalAlignment="Top" Height="96" Width="191">
        <Grid HorizontalAlignment="Left" Height="74" VerticalAlignment="Top" Width="179">
            <Grid.RowDefinitions>
                <RowDefinition Height="1*"/>
                <RowDefinition Height="1*"/>
            </Grid.RowDefinitions>
            <Label Content="Motion:" HorizontalAlignment="Left" VerticalAlignment="Center"/>
            <Label Content="E-mail sending:" HorizontalAlignment="Left" VerticalAlignment="Center" Grid.Row="1"/>
            <Label x:Name="label_Motion" Content="" HorizontalAlignment="Right" VerticalAlignment="Center"/>
            <Label x:Name="label_Email" Content="" HorizontalAlignment="Right" VerticalAlignment="Center" Grid.Row="1"/>

        </Grid>
    </GroupBox>
</Grid>
</Window>
		
Code 2 - GUI example in C#

DISCLAIMER: Please note that the following features will only work if your IP camera supports the given function. You should check the user manual of your IP camera to make sure it supports the feature that you wish to implement in C#.

Related Pages

FAQ

Below you can find the answers for the most frequently asked questions related to this topic:

  1. How can I get the URL of the camera?

    You can get the URL from the producer of the camera. (In the 10th tutorial you can find information on how to create an own IP camera discoverer program.)

  2. I have not managed to build the solution. How to solve it?

    • Please set the Target framework property of the project to .NET 4.0.
    • You should add the System.Drawing.dll and the OzekiSDK.dll to the references of the solution.
    • Please import the missing classes.
  3. I sent a snapshot but I didn't get the email at once. Why?

    • The mail server is overloaded permanently.
    • The uploading speed is low.

More information