دسترسی سریع و آسان: ارسال ایمیل با استفاده از SMTP سرور جیمیل در دات نت C #

This isn’t exactly a new topic, but when I needed to do it, I found a lot of “why won’t this work for me” and not too many direct answers. I hope someone finds this useful.

The following bit of code will send an email using my own gmail account to do it, including attachments:

با استفاده از System.Net.Mail;
با استفاده از System.Net;

NetworkCredential loginInfo = جدید NetworkCredential("[My Gmail ID]", "[My Gmail Password]");
MailMessage msg = جدید MailMessage();
msg.From = جدید MailAddress("[M Gmail Id]@gmail.com");
msg.To.Add(جدید MailAddress("paul.galvin@arcovis.com"));
msg.Subject = "Test infopath dev subject";
msg.Body = "<اچ تی ام ال><بدن><strong>A strong message.</strong></بدن></اچ تی ام ال>";
msg.IsBodyHtml = درست;

حلقه foreach (رشته aFile به NIPFD.GetAttachmentNamesAndLocations())
{
    msg.Attachments.Add(جدید Attachment(aFile));
} // Adding attachments.

SmtpClient client = جدید SmtpClient("smtp.gmail.com");
client.EnableSsl = درست;
client.UseDefaultCredentials = غلط;
client.Credentials = loginInfo;
client.Port = 587;
client.EnableSsl = درست;
client.Send(msg);

A few key bits that slowed me down and other observations / notes:

  • The first line that creates the loginInfo object needs to use the gmail ID stripped of “@gmail.com". پس, if my gmail email address is “sharepoint@gmail.com” and my password is “xyzzy” then the line would look like:

NetworkCredential loginInfo = جدید NetworkCredential("sharepoint", "xyzzy");

  • My gmail account is set up to use SSL and that wasn’t a problem.
  • There is some conflicting information out there on what port to use. I used port 587 and it worked fine for me.
  • در مورد من, I also needed to send attachments. That NIPFD object has a method that knows where my attachments are. It’s returning a fully path (e.g. “c:\temp\attachment1.jpg”. In my test, I had two attachments and they both worked fine.

I used visual studio 2008 to write this code.

</پایان>

مشترک شدن در وبلاگ من.

من در توییتر در http://www.twitter.com/pagalvin

برچسب ها: ,,,

2 دیدگاه در "دسترسی سریع و آسان: ارسال ایمیل با استفاده از SMTP سرور جیمیل در دات نت C #

  1. جف

    The PowerShell Team blog recently had a similar post that I found invaluable as a server admin. Visual Studio is great but many of my peers are not developers and don’t have a license purchased. PowerShell feels more like the command line and is more accessible to them. Just a suggestion for any admins out there.

    بهترین,
    جف (www.spjeff.com / @spjeff)

    Sending Automated emails with Send-MailMessage

    http://blogs.msdn.com/powershell/archive/2009/10/30/sending-automated-emails-with-send-mailmessage-convertto-html-and-the-powershellpack-s-taskscheduler-module.aspx

    پاسخ

پاسخ

آدرس ایمیل شما منتشر نخواهد شد. بخشهای موردنیاز علامتگذاری شدهاند *