从桌面应用程序发送电子邮件 [英] Sending Emails from Desktop Application
本文介绍了从桌面应用程序发送电子邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
大家好,
我开发了一个桌面发送电子邮件应用程序,但是在发送时会生成一个错误,并且异常情况是:发送邮件失败.所以这是代码或我的smtp服务器的问题.请帮帮我,这是我的记下代码.
Hi all ,
I developed a desktop sending email application,but it is generating an error when sending and the exception is saying : failure in sending mail.So is is a problem from the code or from my smtp server.?please help me,and this is my code down.
<pre lang="xml">using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
using System.Text.RegularExpressions;
using System.Web;
namespace EmailHandler
{
public class Emailer
{
/// <summary>
/// Transmit an email message to a recipient without
/// any attachments
/// </summary>
/// <param name="sendTo">Recipient Email Address</param>
/// <param name="sendFrom">Sender Email Address</param>
/// <param name="sendSubject">Subject Line Describing Message</param>
/// <param name="sendMessage">The Email Message Body</param>
/// <returns>Status Message as String</returns>
public static string SendMessage(string sendTo, string sendFrom,
string sendSubject, string sendMessage)
{
try
{
// validate the email address
bool bTest = ValidateEmailAddress(sendTo);
// if the email address is bad, return message
if (bTest == false)
return "Invalid recipient email address: " + sendTo;
// create the email message
MailMessage message = new MailMessage(
sendFrom,
sendTo,
sendSubject,
sendMessage);
// create smtp client at mail server location
SmtpClient client = new SmtpClient(Properties.Settings.Default.SMTPAddress);
// add credentials
client.UseDefaultCredentials = true;
// send message
client.Send(message);
return "Message sent to " + sendTo + " at " + DateTime.Now.ToString() + ".";
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
/// <summary>
/// Transmit an email message with
/// attachments
/// </summary>
/// <param name="sendTo">Recipient Email Address</param>
/// <param name="sendFrom">Sender Email Address</param>
/// <param name="sendSubject">Subject Line Describing Message</param>
/// <param name="sendMessage">The Email Message Body</param>
/// <param name="attachments">A string array pointing to the location of each attachment</param>
/// <returns>Status Message as String</returns>
public static string SendMessageWithAttachment(string sendTo, string sendFrom,
string sendSubject, string sendMessage, ArrayList attachments)
{
try
{
// validate email address
bool bTest = ValidateEmailAddress(sendTo);
if (bTest == false)
return "Invalid recipient email address: " + sendTo;
// Create the basic message
MailMessage message = new MailMessage(
sendFrom,
sendTo,
sendSubject,
sendMessage);
// The attachments arraylist should point to a file location where
// the attachment resides - add the attachments to the message
foreach (string attach in attachments)
{
Attachment attached = new Attachment(attach, MediaTypeNames.Application.Octet);
message.Attachments.Add(attached);
}
// create smtp client at mail server location
SmtpClient client = new SmtpClient(Properties.Settings.Default.SMTPAddress);
client.EnableSsl = true;
// Add credentials
client.UseDefaultCredentials = true;
// send message
client.Send(message);
return "Message sent to " + sendTo + " at " + DateTime.Now.ToString() + ".";
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}
/// <summary>
/// Confirm that an email address is valid
/// in format
/// </summary>
/// <param name="emailAddress">Full email address to validate</param>
/// <returns>True if email address is valid</returns>
public static bool ValidateEmailAddress(string emailAddress)
{
try
{
string TextToValidate = emailAddress;
Regex expression = new Regex(@"\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}");
// test email address with expression
if (expression.IsMatch(TextToValidate))
{
// is valid email address
return true;
}
else
{
// is not valid email address
return false;
}
}
catch (Exception)
{
throw;
}
}
}
}
<pre lang="xml">using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using EmailHandler;
namespace EmailTestApp
{
/// <summary>
/// Test Application Form:
/// This application is used to test sending
/// email and email with attachments.
/// </summary>
public partial class frmTestEmail : Form
{
/// <summary>
/// An arraylist containing
/// all of the attachments
/// </summary>
ArrayList alAttachments;
/// <summary>
/// Default constructor
/// </summary>
public frmTestEmail()
{
InitializeComponent();
}
/// <summary>
/// Add files to be attached to the email message
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnAdd_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
string[] arr = openFileDialog1.FileNames;
alAttachments = new ArrayList();
txtAttachments.Text = string.Empty;
alAttachments.AddRange(arr);
foreach (string s in alAttachments)
{
txtAttachments.Text += s + "; ";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
}
/// <summary>
/// Exit the application
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnCancel_Click(object sender, EventArgs e)
{
Application.Exit();
}
/// <summary>
/// Send an email message with or without attachments
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSend_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(txtSendTo.Text))
{
MessageBox.Show("Missing recipient address.", "Email Error");
return;
}
if (String.IsNullOrEmpty(txtSendFrom.Text))
{
MessageBox.Show("Missing sender address.", "Email Error");
return;
}
if (String.IsNullOrEmpty(txtSubjectLine.Text))
{
MessageBox.Show("Missing subject line.", "Email Error");
return;
}
if (String.IsNullOrEmpty(txtMessage.Text))
{
MessageBox.Show("Missing message.", "Email Error");
return;
}
string[] arr = txtAttachments.Text.Split('';'');
alAttachments = new ArrayList();
for (int i = 0; i < arr.Length; i++)
{
if (!String.IsNullOrEmpty(arr[i].ToString().Trim()))
{
alAttachments.Add(arr[i].ToString().Trim());
}
}
// if there are attachments, send message with
// SendMessageWithAttachment call, else use the
// standard SendMessage call
if (alAttachments.Count > 0)
{
string result = Emailer.SendMessageWithAttachment(txtSendTo.Text,
txtSendFrom.Text, txtSubjectLine.Text, txtMessage.Text,
alAttachments);
MessageBox.Show(result, "Email Transmittal");
}
else
{
string result = Emailer.SendMessage(txtSendTo.Text,
txtSendFrom.Text, txtSubjectLine.Text, txtMessage.Text);
MessageBox.Show(result, "Email Transmittal");
}
}
}
}
推荐答案
您可以做的最好的事情是查看实际的异常:它应该为您提供更多信息,尤其是内部异常.可以在每个catch块中放置断点以查看发生了什么,或者使用菜单中的"Debug ... Exceptions",然后在"Thrown"列中打勾以捕获每个异常,无论是否已处理.
The best thing you can do is to look at the actual exception: it should give you more info, particularly in the inner exception. Either put breakpoints in each catch block to see what is going on, or use "Debug...Exceptions" from the menu and tick everything in the "Thrown" column to catch every exception, whether handled or not.
使用Gmail smtp服务器测试其免费的
smtp.gmail.com端口:587,并使用您的gmail用户名和密码(而不是默认值)并将ssl设置为true.
因为您的smtp服务器似乎有问题
--Pankaj
Use Gmail smtp server for testing its free
smtp.gmail.com port:587 and use your gmail user name and password instead of default and set ssl true.
because its seems problem with your smtp server
--Pankaj
你好,
您可以使用此代码从所有邮件服务器发送电子邮件到
最好的问候
Morteza Shoja
Hello,
You can use this code to send email to from all mail servers
Best Regards
Morteza Shoja
_______________________________________
Imports System.Net
Imports System.Net.Mail
Imports System.Net.Mime
_______________________________________
Private Sub EmailSender(ByVal From As String, ByVal DisplayName As String, ByVal SendTo As String, ByVal Message As String, ByVal Subject As String, ByVal Password As String, ByVal Attach As String)
Using mailMessage As New MailMessage(New MailAddress(SendTo), New MailAddress(SendTo))
mailMessage.Body = Message
mailMessage.Subject = Subject
Try
Dim SmtpServer As New SmtpClient()
SmtpServer.Credentials = New System.Net.NetworkCredential(From, Password)
SmtpServer.Port = 587
Dim MS() As String = From.ToString.Split("@")
Dim MailServer() As String = MS(1).ToString.Split(".")
Select Case UCase(MailServer(0))
Case Is = "GMAIL"
SmtpServer.Host = "smtp.gmail.com"
SmtpServer.EnableSsl = True
Case Is = "YAHOO"
SmtpServer.Host = "smtp.mail.yahoo.com"
SmtpServer.EnableSsl = False
Case Is = "AOL"
SmtpServer.Host = "smtp.aol.com"
SmtpServer.EnableSsl = False
Case Is = "LIVE"
SmtpServer.Credentials = New System.Net.NetworkCredential(From, Password)
SmtpServer.Host = "smtp.live.com"
SmtpServer.EnableSsl = True
End Select
mail = New MailMessage()
Dim addr() As String = SendTo.Split(",")
mail.From = New MailAddress(From, DisplayName, System.Text.Encoding.UTF8)
Dim i As Byte
For i = 0 To addr.Length - 1
mail.To.Add(addr(i))
Next i
mail.Subject = Subject
mail.Body = Message
mail.BodyEncoding = System.Text.Encoding.UTF7
If Attach.Length <> 0 Then
mail.Attachments.Add(New Attachment(Attach))
End If
mail.IsBodyHtml = True
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
mail.ReplyTo = New MailAddress(SendTo)
SmtpServer.Send(mail)
Catch ex As Exception
MessageBox.Show(ex.Message, "EMail", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
End Using
End Sub
这篇关于从桌面应用程序发送电子邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文