Click here to Skip to main content
Click here to Skip to main content

Email Sender

, 12 Jun 2011 CDDL
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Liu Junfeng
Software Developer (Senior) Beyondsoft SH
China China
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 PinmemberCoffeeShop7-Feb-14 5:13 
GeneralMy vote of 5 PinmemberAnsariAzam15-Aug-13 2:27 
GeneralMy vote of 5 PinprofessionalPrasad Khandekar23-May-13 21:01 
GeneralMy vote of 5 PinmemberPolinia8-Mar-13 2:11 
GeneralMy vote of 3 Pinmemberbuntheth22-Oct-12 21:23 
GeneralRe: My vote of 3 Pinprofessionalgggustafson21-Jul-14 11:16 
GeneralMy vote of 5 Pinmemberadriancs15-Oct-12 1:51 
GeneralMy vote of 5 PinmemberJames Eager5-Jul-12 5:44 
QuestionHi, you Pinmembertesulakata5-May-12 23:58 
QuestionEmail Pinmembermichaeldexter26-Jul-11 17:14 
General我顶!!! Pinmemberxut244713-Jun-11 16:26 
GeneralRe: 我顶!!! PinmentorDaveAuld1-Jul-11 11:20 
GeneralRe: 我顶!!! Pinmemberadriancs15-Oct-12 1:47 
GeneralRe: 我顶!!! PinmentorDaveAuld15-Oct-12 1:49 
GeneralRe: 我顶!!! PinmemberRickyJiao10-Dec-12 21:43 
GeneralMy vote of 5 PinmemberWooters13-Jun-11 6:52 
QuestionHow to erase the Spam word on the subject? Pinmemberyoshinosuka26-Dec-10 21:31 
AnswerRe: How to erase the Spam word on the subject? PinmemberDaveAuld23-Feb-11 21:59 
GeneralRe: How to erase the Spam word on the subject? Pinmemberyoshinosuka6-Mar-11 16:12 
GeneralRe: How to erase the Spam word on the subject? PinmemberDaveAuld6-Mar-11 22:17 
GeneralGreat work!!! Very simple and helpful code. Thanks. PinmemberVigen Shahbazian28-Oct-10 5:47 
GeneralAnother alternative Pinmemberdaluu16-Oct-10 21:37 
GeneralThanks Pinmembermsj4u29-May-10 21:45 
GeneralDo not know what's the wrong!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!. PinmemberMd.Aminul Islam1-Apr-09 1:04 
GeneralRe: Do not know what's the wrong!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!. PinmemberLiu Junfeng1-Apr-09 18:50 
GeneralRe: Do not know what's the wrong!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!. PinmemberMd.Aminul Islam1-Apr-09 22:17 
GeneralAuthorisation Issues Pinmemberwilltmpw19-Feb-09 1:09 
GeneralRe: Authorisation Issues PinmemberLiu Junfeng19-Feb-09 2:21 
GeneralNeed more information about the issue Pinmembermohamed samir abdeen14-Jan-09 0:51 
GeneralUnfortunately... PinmemberADLER14-Nov-08 3:13 
GeneralATL C++ alternative Pinmemberdaluu3-Oct-08 21:27 
GeneralCorrect vb2005 Conversion PinmemberTechPrince16-Sep-08 13:01 
QuestionE-mail Sender PinmemberAnonumous9-Jul-08 5:49 
GeneralRe: E-mail Sender Pinmemberianbacalla7-Aug-08 18:24 
GeneralSpam PinmemberMember 445127910-Jun-08 10:41 
GeneralRe: Spam PinmemberFar Side12-Jun-08 10:34 
GeneralI dont catch your meaning for a sentence PinmemberHAROLD CHAO10-Jun-08 2:11 
GeneralRe: I dont catch your meaning for a sentence PinmemberLiu Junfeng10-Jun-08 17:35 
GeneralRe: I dont catch your meaning for a sentence PinmemberHAROLD CHAO11-Jun-08 5:12 
GeneralUse Gmail.. PinmemberPat Tormey10-Jun-08 1:09 
GeneralUse native domain name resolver Pinmemberzulu9-Jun-08 23:51 
GeneralRe: Use native domain name resolver PinmemberLiu Junfeng10-Jun-08 0:12 
GeneralSmtp port not free PinmemberChristian_Anteis9-Jun-08 23:23 
GeneralThe application hangs Pinmemberivanchain@hotmail.com9-Jun-08 23:00 
AnswerRe: The application hangs PinmemberLiu Junfeng9-Jun-08 23:54 
GeneralRegExp Pinmemberazolotko9-Jun-08 20:45 
GeneralRe: RegExp Pinmemberzulu9-Jun-08 23:54 
GeneralRe: RegExp Pinmemberazolotko10-Jun-08 0:30 
GeneralRe: RegExp Pinmemberzulu10-Jun-08 0:57 
Generaldig google.com MX PinmemberLeblanc Meneses9-Jun-08 18:30 

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.

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