📬 什么是 WebMail 帮助器?
WebMail 帮助器 是 ASP.NET Web Pages 提供的内建工具,用于通过 SMTP 协议发送电子邮件。它简化了邮件发送过程,无需手动操作 SmtpClient
类等底层实现。
WebMail 支持基本的邮件功能,如设置发件人、收件人、主题、正文、HTML 内容、附件等。
⚙️ 配置 WebMail
WebMail 需要在使用前进行 SMTP 设置,建议写在 _AppStart.cshtml
或配置文件中:
@{
WebMail.SmtpServer = "smtp.your-email.com";
WebMail.SmtpPort = 587;
WebMail.EnableSsl = true;
WebMail.UserName = "your_email@example.com";
WebMail.Password = "your_password";
WebMail.From = "your_email@example.com";
}
说明:
SmtpServer
: SMTP 主机地址(如 Gmail 是smtp.gmail.com
)SmtpPort
: 通常是 25, 465 或 587EnableSsl
: 是否启用 SSLUserName
: 登录邮箱账户Password
: 登录密码(或应用专用密码)From
: 发件人地址
📤 发送基本邮件示例
@{
var to = "target@example.com";
var subject = "欢迎访问我们的网站";
var body = "感谢您的注册,我们很高兴为您服务。";
WebMail.Send(to, subject, body);
}
🧾 发送 HTML 格式的邮件
@{
WebMail.Send(
to: "target@example.com",
subject: "HTML 邮件示例",
body: "<h1>欢迎!</h1><p>这是 HTML 格式的邮件。</p>",
isBodyHtml: true
);
}
📎 发送带附件的邮件
@{
WebMail.Send(
to: "target@example.com",
subject: "发送附件",
body: "请查收附件。",
filesToAttach: new[] { Server.MapPath("~/files/report.pdf") }
);
}
🧪 表单邮件提交案例
@{
if (IsPost) {
var name = Request["name"];
var message = Request["message"];
WebMail.Send(
to: "admin@example.com",
subject: "用户留言",
body: "用户 " + name + " 发送了信息:" + message
);
}
}
<form method="post">
<label>姓名:</label>
<input type="text" name="name" />
<br />
<label>留言:</label>
<textarea name="message"></textarea>
<br />
<input type="submit" value="发送" />
</form>
❗ 安全建议
- 避免将用户名和密码硬编码在
.cshtml
页面中,建议使用配置文件或数据库存储。 - Gmail 等服务可能要求启用“应用专用密码”。
- SMTP 配置错误会引发异常,请使用 try-catch 包裹
WebMail.Send()
调用。
🧯 异常处理
@try {
WebMail.Send("someone@example.com", "主题", "内容");
<p>邮件已发送。</p>
}
catch (Exception ex) {
<p>邮件发送失败:@ex.Message</p>
}
🌐 出站链接推荐
📚 参考资料
- Microsoft Learn – ASP.NET Web Pages: WebMail Helper
- 《ASP.NET 入门经典》邮件发送章节
- W3Schools – Razor WebMail Helper 指南
发表回复