Chapter 13: WebPages Mail
WebPages Email
This helper is one of the most practical built-in tools in ASP.NET Web Pages. It lets you send emails directly from your .cshtml pages using SMTP — think contact forms, password reset emails, order confirmations, newsletters, or support tickets.
No external libraries needed — just configure once, and send with one or two lines of code!
1. What is the WebMail Helper? (The Big Picture)
WebMail is a static class (System.Web.Helpers.WebMail) that provides everything you need to send emails via SMTP (Simple Mail Transfer Protocol — the standard way emails travel over the internet).
Key points from W3Schools and Microsoft docs:
- Super simple: Set SMTP server details once → call WebMail.Send(…)
- Supports HTML emails, attachments, CC/BCC, priority
- Works with Gmail, Outlook.com, your hosting provider’s SMTP, or any SMTP server
- Important: Configuration usually goes in _AppStart.cshtml (global startup file we learned about earlier) so it’s set once for the whole site.
Without it, you’d have to write low-level System.Net.Mail code — messy and error-prone. WebMail hides all that.
2. Step 1: Configure WebMail (Do This Once!)
Put this in ~/App_Data/_AppStart.cshtml (or root _AppStart if no App_Data) — it runs automatically on app start.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@{ // Global email setup - runs once when site starts WebMail.SmtpServer = "smtp.gmail.com"; // or your host's SMTP server WebMail.SmtpPort = 587; // 587 for TLS, 465 for SSL WebMail.EnableSsl = true; // almost always true nowadays WebMail.UserName = "yourname@gmail.com"; // your email address WebMail.Password = "your-app-password-or-key"; // NEVER use main password! WebMail.From = "yourname@gmail.com"; // default sender (can override per email) } |
Real-world notes (very important 2026 advice):
- For Gmail: Use an App Password (not your regular password). Go to Google Account → Security → App passwords → generate one for “Mail” on “Windows Computer”.
- For Microsoft 365/Outlook: Use smtp.office365.com, port 587, your full email + password/app password.
- For production hosting (e.g., Azure, Godaddy, Hostinger): Use their provided SMTP settings — often no auth needed if from same domain.
- Security: Never hardcode passwords in code! In real apps use web.config<appSettings> or environment variables/secrets manager.
- Test first with your own email!
3. Step 2: Sending an Email – Basic Example
File: Contact.cshtml (contact form page)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
@{ var messageSent = false; var errorMessage = ""; if (IsPost) { var customerName = Request["name"]; var customerEmail = Request["email"]; var subject = Request["subject"]; var body = Request["message"]; // Basic validation (add more later with Validation helper) if (String.IsNullOrEmpty(customerEmail) || String.IsNullOrEmpty(body)) { errorMessage = "Please fill in email and message."; } else { try { WebMail.Send( to: "support@yourwebsite.com", // recipient subject: "Contact Form: " + (subject ?? "No Subject"), body: $@" <h3>New Contact Message</h3> <p><strong>From:</strong> {customerName} ({customerEmail})</p> <p><strong>Message:</strong><br>{body.Replace("\n", "<br>")}</p>", isBodyHtml: true, // HTML email replyTo: customerEmail // so reply goes to customer ); messageSent = true; } catch (Exception ex) { errorMessage = "Sorry, email could not be sent: " + ex.Message; } } } } <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Contact Us</title> </head> <body> <h1>Contact Support Team</h1> @if (messageSent) { <div style="color: green; font-weight: bold; padding: 15px; border: 1px solid green;"> <p>Thank you! Your message has been sent successfully. We'll reply soon 😊</p> </div> } else if (!String.IsNullOrEmpty(errorMessage)) { <div style="color: red; padding: 10px; border: 1px solid red;"> @errorMessage </div> } <form method="post"> <label>Your Name:</label><br> <input type="text" name="name" size="40" /><br><br> <label>Your Email:</label><br> <input type="email" name="email" size="40" required /><br><br> <label>Subject:</label><br> <input type="text" name="subject" size="40" /><br><br> <label>Message:</label><br> <textarea name="message" rows="6" cols="50" required></textarea><br><br> <input type="submit" value="Send Message" /> </form> </body> </html> |
What happens?
- User fills form → submits
- IsPost → true
- Read form fields with Request[…]
- WebMail.Send(…) → sends email
- to: who receives it
- subject: line
- body: can be plain text or HTML
- isBodyHtml: true → enables <h3>, <br>, etc.
- replyTo: smart — reply button goes to customer
- Show success or error message
4. Advanced Options (Quick Extras from Docs)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
WebMail.Send( to: "team@company.com, manager@company.com", // multiple recipients (comma separated) cc: "boss@company.com", bcc: "archive@company.com", subject: "Urgent Order #1234", body: "<h1>Order Confirmed</h1><p>Details...</p>", isBodyHtml: true, priority: WebMailPriority.High, filesToAttach: new[] { Server.MapPath("~/uploads/invoice.pdf") } // attachment! ); |
5. Teacher Warnings & Best Practices (2026 Edition)
- Never expose SMTP credentials in client-side code — always server-side
- Use TLS/SSL (EnableSsl = true) — almost all servers require it now
- Gmail limits: ~100–500 emails/day — use transactional services (SendGrid, Mailgun) for production
- No built-in queue — for high volume → use background jobs or external service
- Modern equivalent in ASP.NET Core → IEmailSender + MailKit / FluentEmail (more flexible, async)
- Test thoroughly — send to yourself first, check spam folder!
Summary – Like Closing the Class
ASP.NET Web Pages WebMail Helper = easy SMTP email sender:
- Configure once in _AppStart.cshtml (SmtpServer, Port, Credentials, From)
- Send with WebMail.Send(to, subject, body, isBodyHtml: true, …)
- Perfect for contact forms, notifications, confirmations
- Simple → one method call after setup
You’ve now covered forms + databases + grids + charts + email — your sites are becoming full-featured apps!
Next?
- Want to add attachment (e.g., user uploads resume)?
- Combine with WebGrid (email report of sales data)?
- Or jump to WebPages Security (login + password reset emails)?
Tell me — you’re absolutely killing this tutorial track from Hyderabad! Keep shining! 🚀🇮🇳
