Click here to Skip to main content
Licence CDDL
First Posted 4 Jun 2008
Views 77,534
Downloads 3,157
Bookmarked 105 times

Email Sender

By | 12 Jun 2011 | Article
Send email directly to the receiver's SMTP server.

sender.png

Introduction

Usually, when we send an email, we need to login to a known email service provider's SMTP server and deliver the email using that server. If we add the send email functionality to a software, the user needs to configure an SMTP server address, the username, and the password. Why not send an email to the receiver's SMTP server directly? Because the receiver's server doesn't need authorization, otherwise you can only receive email when the sender knows your account password. I think many programmers have been asking this question, so I explored the issue.

The problem is we don't know which SMTP server is responsible for receiving emails for a given email address. The secret is that this information can be obtained from Domain Name System (DNS) servers. This seems simple; however, it needs a lot work to implement the DNS protocol (RFC 1035) because the .NET Framework doesn't support getting mail server info from DNS. Once we have the SMTP server address, we can send emails to the receiver directly!

Using the code

I partially implemented the DNS protocol in four classes: DnsMessage, DnsQuery, DnsResource, and DnsMessageCoder. Then, I wrapped the functionality in the DomainNameUtil class.

Now, EmailSender can use DomainNameUtil to get the mail server from the email address and send the email:

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Mail;
namespace QiHe.CodeLib.Net
{
    public class EmailSender
    {
        /// <summary>
        /// Default SMTP Port.
        /// </summary>
        public static int SmtpPort = 25;

        public static bool Send(string from, string to, string subject, string body)
        {
            string domainName = GetDomainName(to);
            IPAddress[] servers = GetMailExchangeServer(domainName);
            foreach (IPAddress server in servers)
            {
                try
                {
                    SmtpClient client = new SmtpClient(server.ToString(), SmtpPort);
                    client.Send(from, to, subject, body);
                    return true;
                }
                catch
                {
                    continue;
                }
            }
            return false;
        }

        public static bool Send(MailMessage mailMessage)
        {
            string domainName = GetDomainName(mailMessage.To[0].Address);
            IPAddress[] servers = GetMailExchangeServer(domainName);
            foreach (IPAddress server in servers)
            {
                try
                {
                    SmtpClient client = new SmtpClient(server.ToString(), SmtpPort);
                    client.Send(mailMessage);
                    return true;
                }
                catch
                {
                    continue;
                }
            }
            return false;
        }

        public static string GetDomainName(string emailAddress)
        {
            int atIndex = emailAddress.IndexOf('@');
            if (atIndex == -1)
            {
                throw new ArgumentException("Not a valid email address", 
                                            "emailAddress");
            }
            if (emailAddress.IndexOf('<') > -1 && 
                emailAddress.IndexOf('>') > -1)
            {
                return emailAddress.Substring(atIndex + 1, 
                       emailAddress.IndexOf('>') - atIndex);
            }
            else
            {
                return emailAddress.Substring(atIndex + 1);
            }
        }

        public static IPAddress[] GetMailExchangeServer(string domainName)
        {
            IPHostEntry hostEntry = 
              DomainNameUtil.GetIPHostEntryForMailExchange(domainName);
            if (hostEntry.AddressList.Length > 0)
            {
                return hostEntry.AddressList;
            }
            else if (hostEntry.Aliases.Length > 0)
            {
                return System.Net.Dns.GetHostAddresses(hostEntry.Aliases[0]);
            }
            else
            {
                return null;
            }
        }
    }
}

The user interface is naive; multi-threading and message logging have not been done.

Points of interest

If you have a typo error in the sender email address or use a fake address, the email can still be sent, but this way, you can't expect the receiver to reply to you.

Some systems, e.g., SPF, will check if the sender's IP is declared as a domain name or not. This makes it unreliable to send the email to any address.

In addition, don't send spam emails using my tool or the underlying source code!

History

  • 2008-06-05 - Article submitted.
  • 2011-06-11 - Updated introduction text.

License

This article, along with any associated source code and files, is licensed under The Common Development and Distribution License (CDDL)

About the Author

Liu Junfeng

Software Developer

China China

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionHi, you Pinmembertesulakata22:58 5 May '12  
QuestionEmail Pinmembermichaeldexter16:14 26 Jul '11  
General我顶!!! Pinmemberxut244715:26 13 Jun '11  
GeneralRe: 我顶!!! PinmentorDaveAuld10:20 1 Jul '11  
GeneralMy vote of 5 PinmemberWooters5:52 13 Jun '11  
QuestionHow to erase the Spam word on the subject? Pinmemberyoshinosuka20:31 26 Dec '10  
AnswerRe: How to erase the Spam word on the subject? PinmemberDaveAuld20:59 23 Feb '11  
GeneralRe: How to erase the Spam word on the subject? Pinmemberyoshinosuka15:12 6 Mar '11  
GeneralRe: How to erase the Spam word on the subject? PinmemberDaveAuld21:17 6 Mar '11  
GeneralGreat work!!! Very simple and helpful code. Thanks. PinmemberVigen Shahbazian4:47 28 Oct '10  
GeneralAnother alternative Pinmemberdaluu20:37 16 Oct '10  
GeneralThanks Pinmembermsj4u20:45 29 May '10  
GeneralDo not know what's the wrong!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!. PinmemberMd.Aminul Islam0:04 1 Apr '09  
GeneralRe: Do not know what's the wrong!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!. PinmemberLiu Junfeng17:50 1 Apr '09  
GeneralRe: Do not know what's the wrong!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!. PinmemberMd.Aminul Islam21:17 1 Apr '09  
GeneralAuthorisation Issues Pinmemberwilltmpw0:09 19 Feb '09  
GeneralRe: Authorisation Issues PinmemberLiu Junfeng1:21 19 Feb '09  
GeneralNeed more information about the issue Pinmembermohamed samir abdeen23:51 13 Jan '09  
hi
i am so interested in your article but can you give me example on the issue itself so can go deep through the article i wait your answer as soon as possible
GeneralUnfortunately... PinmemberADLER12:13 4 Nov '08  
GeneralATL C++ alternative Pinmemberdaluu20:27 3 Oct '08  
GeneralCorrect vb2005 Conversion PinmemberTechPrince12:01 16 Sep '08  
QuestionE-mail Sender PinmemberAnonumous4:49 9 Jul '08  
GeneralRe: E-mail Sender Pinmemberianbacalla17:24 7 Aug '08  
GeneralSpam PinmemberMember 44512799:41 10 Jun '08  
GeneralRe: Spam PinmemberFar Side9:34 12 Jun '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120529.1 | Last Updated 12 Jun 2011
Article Copyright 2008 by Liu Junfeng
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid