Sending
Mail With Attachment in Win Forms Using C#
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.Collections;
using
System.Net;
using
System.Net.Mail;
namespace
mail_with_attachment
{
public partial class Form1 : Form
{
ArrayList
alAttachments;
MailMessage
mailMessage;
public
Form1()
{
InitializeComponent();
}
private
void Form1_Load(object
sender, EventArgs e)
{
}
private
void button3_Click(object
sender, EventArgs e)
{
OpenFileDialog
ofdlg = new OpenFileDialog();
if
(ofdlg.ShowDialog() == DialogResult.OK)
{
try
{
textBox7.Text = ofdlg.FileName;
}
catch
(Exception ex)
{
MessageBox.Show(ex.Message,
"Error");
}
}
}
private
void button1_Click(object
sender, EventArgs e)
{
try
{
if
(textBox1.Text != null && textBox2.Text
!= null)
{
mailMessage = new MailMessage(textBox1.Text,
textBox4.Text);
mailMessage.Subject =
textBox5.Text;
mailMessage.Body =
textBox6.Text;
mailMessage.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(textBox1.Text,
textBox2.Text);
//Attachment
Attachment
attachment = new Attachment(textBox7.Text);
if
(attachment != null)
{
mailMessage.Attachments.Add(attachment);
}
//this will be the true in case of gamil and it varies from the service provider
smtpClient.EnableSsl = true;
smtpClient.Send(mailMessage);
}
string
msg = "Message Send Successfully:";
msg += "\n
To :" + textBox4.Text;
MessageBox.Show(msg.ToString());
/*
clear the controls */
textBox1.Text = string.Empty;
textBox2.Text = string.Empty;
textBox3.Text = string.Empty;
textBox4.Text = string.Empty;
textBox5.Text = string.Empty;
textBox6.Text = string.Empty;
textBox7.Text = string.Empty;
}
catch
(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private
void button2_Click(object
sender, EventArgs e)
{
Application.Exit();
}
}
}
I can use this Code
ReplyDeleteBut Show Error
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.0 Authentication Required.
How Can i Slove It
Its Not Wprking
ReplyDelete