65.9K
CodeProject 正在变化。 阅读更多。
Home

如何通过 VB.NET 或 C# 从您的 GMAIL 帐户发送电子邮件。Windows 编程,附带一些自定义

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.12/5 (90投票s)

2007年9月18日

CPOL

5分钟阅读

viewsIcon

633117

downloadIcon

43555

从您的 Windows 应用程序发送邮件

发布 2 的更新

引言

使用您的 Google 邮件客户端通过 Windows 程序发送电子邮件是一种好方法。通常,我们大多数没有自己的邮件主机的人都可以使用这个简单的代码来制作一个能够向任何 SMTP 网站主机发送电子邮件的程序。我已经制作了一个,并想与大家分享。请评论如何使它更具吸引力。非常感谢。

背景

要掌握这个主题,建议您了解一些 VB.NET 的功能,以便能够理解代码。该程序是为用 VB.NET 构建的 Windows 应用程序设计的。所以你需要了解 VB.NET 的相关知识。稍后,我将发布其他文章,允许从您的 Web 应用程序以及 C# 中使用它。

Using the Code

如果您正在阅读代码,我首先包含了一个名为 System.Net.Mail 的命名空间,这样我就不必记住创建其中类的对象的完整命名空间路径。您首先需要从该命名空间创建一个 MailMessage 类的对象。我的表单名为 Mailform,因此对其的引用与我自己的 Windows 表单类有关。在表单加载时,我已将一个只读的 textbox(一个 formtext 框)分配给我的 Gmail 帐户地址。这个 textbox 将用于发送电子邮件。所以在这里,您输入您自己的邮件帐户地址。稍后,我创建了一个名为 SmtpClient 类的对象,名为 SmtpServer。此对象用于通过 NetworkCredentials 发送我的 mailmessage。如果您有自己的主机,则不需要将 networkcredentials 附加到 SmtpServer.Credentials。在这里,在构造函数中,我添加了我的电子邮件地址和密码,当您创建自己的应用程序时,请使用您自己的。接下来是 portnumber,Gmail 发送电子邮件的端口号是 587。所以您应该显式使用它。另外,当您使用 Gmail 时,需要将 EnableSsl 设置为 true,因为 Gmail 需要安全身份验证;smtpserver.send(mail) 实际上是在发送电子邮件。

使用 VB.NET 的代码
//
// Simple application to send mails to any mail clients from Gmail account
// Using VB.NET
Imports System.Net.Mail
Public Class mailform
    Dim mail As New MailMessage()

   Private Sub mailform_Load(ByVal sender As System.Object, ByVal e As _
                System.EventArgs) Handles MyBase.Load
        TextBox2.Text = "xyz@gmail.com"
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles Button1.Click
        Dim SmtpServer As New SmtpClient()
        SmtpServer.Credentials = New Net.NetworkCredential
                    ("xyz@gmail.com", "password")
        SmtpServer.Port = 587
        SmtpServer.Host = "smtp.gmail.com"
        SmtpServer.EnableSsl = True

        mail = New MailMessage()
        Dim addr() As String = TextBox1.Text.Split(",")
        Try
            mail.From = New MailAddress("xyz@gmail.com",
                "Web Developers", System.Text.Encoding.UTF8)

            Dim i As Byte
            For i = 0 To addr.Length - 1
                mail.To.Add(addr(i))
            Next
            mail.Subject = TextBox3.Text
            mail.Body = TextBox4.Text
            If ListBox1.Items.Count <> 0 Then
                For i = 0 To ListBox1.Items.Count - 1
                    mail.Attachments.Add(New Attachment
                        (ListBox1.Items.Item(i)))
                Next
            End If
            mail.DeliveryNotificationOptions =
                    DeliveryNotificationOptions.OnFailure
            mail.ReplyTo = New MailAddress(TextBox1.Text)
            SmtpServer.Send(mail)
        Catch ex As Exception
            MsgBox(ex.ToString())
        End Try
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, _
            ByVal e As System.EventArgs) Handles Button2.Click
        If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            ListBox1.Items.Add(OpenFileDialog1.FileName)
        End If
    End Sub
End Class
使用 C# 的代码
//
// Simple application to send mails to any mail clients from Gmail account
// Using C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net.Mime;
namespace Gmail
{
    public partial class Form1 : Form
    {
        String path;
        MailMessage mail = new MailMessage();
        public Form1()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            SmtpClient SmtpServer = new SmtpClient();
            SmtpServer.Credentials = new System.Net.NetworkCredential
                        ("xyz@gmail.com", "password");
            SmtpServer.Port = 587;
            SmtpServer.Host = "smtp.gmail.com";
            SmtpServer.EnableSsl = true;
            mail = new MailMessage();
            String[] addr = TextBox1.Text.Split(',');
            try
            {
                mail.From = new MailAddress("xyz@gmail.com",
                "Developers", System.Text.Encoding.UTF8);
                Byte i;
                for( i = 0;i< addr.Length; i++)
                    mail.To.Add(addr[i]);
                mail.Subject = TextBox3.Text;
                mail.Body = TextBox4.Text;
                if(ListBox1.Items.Count != 0)
                {
                    for(i = 0;i<ListBox1.Items.Count;i++)
          mail.Attachments.Add(new Attachment(ListBox1.Items[i].ToString()));
                }
          mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                mail.ReplyTo = new MailAddress(TextBox1.Text);
                SmtpServer.Send(mail);
            }
            catch (Exception ex){
            MessageBox.Show(ex.ToString());
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            TextBox2.Text = "xyz@gmail.com";
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            if(OpenFileDialog1.ShowDialog()== DialogResult.OK)
            {
                ListBox1.Items.Add(OpenFileDialog1.FileName);
            }
        }
    }
} 

您需要将您的用户 ID 从 xyz@gmail.com 更改为您自己的 Gmail 用户 ID,并将密码从“Password”更改为您自己的密码。

这是 Windows 窗体的快照。请查看。

Screenshot - coolimage.jpg

发布 2 的更新

在此更新中,我添加了一些技巧,以便您可以在 Gmail 客户端中嵌入图像,并轻松发送带有公司徽标的电子邮件。只需从本文顶部的链接下载代码并遵循即可。

使用 VB.NET 的代码
//Using VB.NET
Imports System.Net.Mail
Imports System.Net.Mime

Public Class mailform
    Dim path As String
    Dim mail As New MailMessage()
    Private Sub mailform_Disposed(ByVal sender As Object,
            ByVal e As System.EventArgs) Handles Me.Disposed
        End
    End Sub

    Private Sub mailform_Load(ByVal sender As System.Object,
        ByVal e As System.EventArgs) Handles MyBase.Load
        TextBox2.Text = "xyz@gmail.com"
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object,
            ByVal e As System.EventArgs) Handles Button1.Click
        Dim SmtpServer As New SmtpClient()
        SmtpServer.Credentials = New Net.NetworkCredential("xyz@gmail.com",
                                "password")
        SmtpServer.Port = 587
        SmtpServer.Host = "smtp.gmail.com"
        SmtpServer.EnableSsl = True
        mail = New MailMessage()
        Dim addr() As String = TextBox1.Text.Split(",")
        Try
            mail.From = New MailAddress("xyz@gmail.com", "Developers",
                        System.Text.Encoding.UTF8)
            Dim i As Byte
            For i = 0 To addr.Length - 1
                mail.To.Add(addr(i))
            Next
            mail.Subject = TextBox3.Text
            'mail.Body = TextBox4.Text
            If ListBox1.Items.Count <> 0 Then
                For i = 0 To ListBox1.Items.Count - 1
                  mail.Attachments.Add(New Attachment(ListBox1.Items.Item(i)))
                Next
            End If
            Dim logo As New LinkedResource(path)
            logo.ContentId = "Logo"
            Dim htmlview As String
            htmlview = "<html><body><table border=2><tr width=100%><td>
        <img src=cid:Logo alt=companyname /></td>
        <td>MY COMPANY DESCRIPTION</td></tr></table>
                        <hr/></body></html>"
            Dim alternateView1 As AlternateView =
        AlternateView.CreateAlternateViewFromString(htmlview +
              TextBox4.Text, Nothing, MediaTypeNames.Text.Html)
            alternateView1.LinkedResources.Add(logo)
            mail.AlternateViews.Add(alternateView1)
            mail.IsBodyHtml = True
            mail.DeliveryNotificationOptions =
                DeliveryNotificationOptions.OnFailure
            mail.ReplyTo = New MailAddress(TextBox1.Text)
            SmtpServer.Send(mail)
        Catch ex As Exception
            MsgBox(ex.ToString())
        End Try
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object,
            ByVal e As System.EventArgs) Handles Button2.Click
        If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            ListBox1.Items.Add(OpenFileDialog1.FileName)
        End If
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object,
            ByVal e As System.EventArgs) Handles Button4.Click
        Dim d1 As New OpenFileDialog()
        If d1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            path = d1.FileName
            TextBox5.Text = d1.FileName
        End If
    End Sub
End Class
使用 C# 的代码
//Using C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Mail;
using System.Net.Mime;
namespace Gmail
{
    public partial class Form1 : Form
    {
        String path;
        MailMessage mail = new MailMessage();
        public Form1()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            SmtpClient SmtpServer = new SmtpClient();
 SmtpServer.Credentials = new System.Net.NetworkCredential
                        ("xyz@gmail.com", "password");
            SmtpServer.Port = 587;
            SmtpServer.Host = "smtp.gmail.com";
            SmtpServer.EnableSsl = true;
            mail = new MailMessage();
            String[] addr = TextBox1.Text.Split(',');
            try
            {
                mail.From = new MailAddress("xyz@gmail.com",
                "Developers", System.Text.Encoding.UTF8);
                Byte i;
                for( i = 0;i< addr.Length; i++)
                    mail.To.Add(addr[i]);
                mail.Subject = TextBox3.Text;
                mail.Body = TextBox4.Text;
                if(ListBox1.Items.Count != 0)
                {
                    for(i = 0;i<ListBox1.Items.Count;i++)
                    mail.Attachments.Add(new Attachment(ListBox1.Items[i].ToString()));
                }
                LinkedResource logo = new LinkedResource(path);
                logo.ContentId = "Logo";
                string htmlview;
 htmlview = "<html><body><table border=2><tr width=100%><td>
    <img src=cid:Logo alt=companyname /></td><td>MY COMPANY DESCRIPTION
                </td></tr></table><hr/></body></html>";
 AlternateView alternateView1 = AlternateView.CreateAlternateViewFromString
           (htmlview + TextBox4.Text, null, MediaTypeNames.Text.Html);
                alternateView1.LinkedResources.Add(logo);
                mail.AlternateViews.Add(alternateView1);
                mail.IsBodyHtml = true;
 mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
                mail.ReplyTo = new MailAddress(TextBox1.Text);
                SmtpServer.Send(mail);
            }
            catch (Exception ex){
            MessageBox.Show(ex.ToString());
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            TextBox2.Text = "xyz@gmail.com";
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            if(OpenFileDialog1.ShowDialog()== DialogResult.OK)
            {
                ListBox1.Items.Add(OpenFileDialog1.FileName);
            }
        }

        private void Button4_Click(object sender, EventArgs e)
        {
            OpenFileDialog d1 = new OpenFileDialog();
             if(d1.ShowDialog() == DialogResult.OK)
             {
                path = d1.FileName;
                TextBox5.Text = d1.FileName;
            }
        }
    }
} 

在这里的代码中,我使用 HTML 发送我的电子邮件,而不是发送纯文本格式,这样我就可以在电子邮件中嵌入图像。好吧,要发送 HTML 格式的电子邮件,我在 CreateAlternateViewFromString 中使用了 MediaTypeNames.Text.Html。此备用视图类用于在 Web 客户端中格式化电子邮件的视图。此格式化视图可以是文本、HTML、XML、RichText 等。我在这里使用 HTML。在我的 htmlview string 变量中,我制作了要显示的初始徽标。linkedResource 类的构造函数接受一个文件路径,该路径取自另一个 OpenFileDialog 框。这将在电子邮件正文中创建嵌入资源。因此,我使用此功能通过 HTML 将图像资源显示给我的客户端。在我的 HTML 中,我使用了相同的 contentId,即“logo”,通过写入 cid:Logo 来引用链接到 mailmessage 的图像文件。现在看下面的快照

Screenshot - coolimage2.jpg

发送消息后,它将显示为

Screenshot - coolimage3.jpg

检查一下。在您的电子邮件消息中使用嵌入式图像,即使您在 Outlook 或任何电子邮件客户端中离线,也能看到这些图像,因为此徽标通常会被缓存。

我认为这个修改可能会有所帮助。

更新 3

在此更新中,我为应用程序添加了一些自定义功能。我已将一些指定值存储到注册表中。我没有在这里包含加密,以便初学者更容易理解。对于想要使用我的软件的高级用户,我一定会发布一个包含所有安全措施的版本。

//Login Form
public partial class Login : Form
    {
        private string userid;
        private string password;
        private RegistryKey hklmu;
        private RegistryKey hklmp;

        public string UserID
        {
            get
            {
                userid = hklmu.GetValue("uid").ToString();
                return userid;
            }
            set
            {

                hklmu.SetValue("uid", value.ToString());
                userid = value;
            }
        }
        public string Password
        {
            get
            {
                password  = hklmp.GetValue("passwd").ToString();
                return password;
            }
            set
            {

                hklmp.SetValue("passwd", value.ToString());
                password = value;
            }
        }

        public Login()
        {
            InitializeComponent();
            hklmu = Registry.LocalMachine;
            hklmp = Registry.LocalMachine;
            hklmp = hklmp.OpenSubKey("SOFTWARE\\GmailClient",true);
            hklmu = hklmu.OpenSubKey("SOFTWARE\\GmailClient",true);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.UserID = textBox1.Text;
            this.Password = textBox2.Text;
            this.Hide();
        }

        private void Login_Load(object sender, EventArgs e)
        {
            textBox1.Text = this.UserID;
            textBox2.Text = this.Password;
        }

//Preview Form
public partial class Preview : Form
    {
        private string _document;

        public string Document
        {
            get { return _document; }
            set { _document = value; }
        }

        public Preview()
        {
            InitializeComponent();
        }

        private void Preview_Load(object sender, EventArgs e)
        {
            this.webBrowser1.DocumentText = this.Document;

        }
    }

//Save background Profile Info
public partial class ChangeProfile : Form
    {
        private RegistryKey hklm;
        public ChangeProfile()
        {
            InitializeComponent();
            hklm = Registry.LocalMachine;
            hklm = hklm.OpenSubKey("SOFTWARE\\GmailClient", true);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            hklm.SetValue("name", textBox1.Text);
            hklm.SetValue("address", textBox2.Text);
            hklm.SetValue("ph", textBox3.Text);
            hklm.SetValue("work", textBox4.Text);
            hklm.SetValue("quote", textBox6.Text);
            hklm.SetValue("website", textBox5.Text);
            this.Dispose();
        }

        private void ChangeProfile_Load(object sender, EventArgs e)
        {
            textBox1.Text = hklm.GetValue("name").ToString();
            textBox2.Text = hklm.GetValue("address").ToString();
            textBox3.Text = hklm.GetValue("ph").ToString();
            textBox4.Text = hklm.GetValue("work").ToString();
            textBox6.Text = hklm.GetValue("website").ToString();
            textBox5.Text = hklm.GetValue("quote").ToString();
        }
    }

下面显示了一些图片

Sending_Emails_From_GMAIL/coolimageupdate1.jpg

Sending_Emails_From_GMAIL/coolimageupdate2.jpg

Sending_Emails_From_GMAIL/coolimageupdate3.jpg

您可以看到……这些是我的项目中包含的附件,可以帮助您直接从界面进行工作。

希望收到您的好反馈。谢谢。

关注点

没什么。看看就行了,也许下次会有什么东西。

历史

  • 发布 1: 这是我的第一个代码发布。请告诉我可以使用哪些网络凭据向 Yahoo、Hotmail 等其他邮件客户端发送电子邮件。希望得到一些好的回复。
  • 发布 2: 在此版本中,我添加了另一个有用的功能,以便您可以从 Gmail 帐户发送嵌入式图像;非常适合发送您的公司徽标。此图像是嵌入式资源,将与您的电子邮件文本一起缓存。查看我的新版本。它有效。
  • 发布 3: 在此版本中,我通过添加相同的 C# 代码修改了文章,以便 C# 程序员也能从这段代码中受益。
  • 发布 4: 在此版本中,我进行了一些与配置文件相关的修改。

非常感谢大家。希望这能帮助到您。编程愉快!

© . All rights reserved.