You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC集成Gmail API:邮件显示与SQL存储技术问询

解决ASP.NET MVC展示Gmail邮件列表及存储到SQL Server的问题

一、修复邮件数据无法传递到视图的问题

你的代码存在逻辑顺序错误:在判断ReadableText是否为空并添加邮件到列表时,ReadableText还未被解码赋值,导致EmailList始终为空,视图自然无法显示数据。同时代码中存在语法错误,需一并修正。

修改后的GetAllEmails核心代码

// ... 其他代码保持不变
MailBody = string.Empty;
if (MsgContent.Payload.Parts == null && MsgContent.Payload.Body != null)
{
    MailBody = MsgContent.Payload.Body.Data;
}
else
{
    MailBody = GmailAPIHelper.MsgNestedParts(MsgContent.Payload.Parts);
}
// 先解码获取可读文本,再判断添加到列表
ReadableText = GmailAPIHelper.Base64Decode(MailBody);
if (!string.IsNullOrEmpty(ReadableText))
{
    Gmail GMail = new Gmail();
    GMail.From = FromAddress;
    GMail.Body = ReadableText;
    // 处理Date字符串转DateTime,避免格式异常
    if (DateTime.TryParse(Date, out DateTime mailDate))
    {
        GMail.MailDateTime = mailDate;
    }
    GMail.MsgID = Msg.Id;
    // 补充Subject字段(原代码中获取了Subject但未赋值)
    GMail.Subject = Subject;
    // 绑定附件列表
    GMail.Attachments = FileName;
    EmailList.Add(GMail);
}

// 修正FromAdd替换的语法错误
if (FileName.Count() > 0)
{
    foreach (var EachFile in FileName)
    {
        string[] RectifyFromAddress = FromAddress.Split(' ');
        string FromAdd = RectifyFromAddress[RectifyFromAddress.Length - 1];
        if (!string.IsNullOrEmpty(FromAdd))
        {
            FromAdd = FromAdd.Replace("<", string.Empty);
            FromAdd = FromAdd.Replace(">", string.Empty);
        }
    }
}
// ... 其他代码保持不变

二、创建Index视图展示邮件列表

在Views/Email/Index.cshtml中添加以下代码,接收List<Gmail>模型并循环展示:

@model List<WebApplication3.Models.Gmail>

<h2>收件箱未读邮件</h2>

@if (Model != null && Model.Count > 0)
{
    <table class="table table-striped">
        <thead>
            <tr>
                <th>发件人</th>
                <th>主题</th>
                <th>接收时间</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var email in Model)
            {
                <tr>
                    <td>@email.From</td>
                    <td>@email.Subject</td>
                    <td>@email.MailDateTime.ToString("yyyy-MM-dd HH:mm")</td>
                    <td>
                        <a href="@Url.Action("Detail", "Email", new { id = email.MsgID })" class="btn btn-sm btn-primary">查看详情</a>
                    </td>
                </tr>
            }
        </tbody>
    </table>
}
else
{
    <p>暂无未读邮件</p>
}

若需展示邮件详情,可新增Detail Action和视图,根据MsgID重新获取并渲染邮件内容。

三、将邮件数据存储到MS SQL Server

1. 配置Entity Framework(推荐)

先安装Entity Framework NuGet包:

Install-Package EntityFramework

2. 创建数据库上下文类

using System.Data.Entity;
using WebApplication3.Models;

namespace WebApplication3.Data
{
    public class EmailDbContext : DbContext
    {
        public EmailDbContext() : base("name=EmailDbConnection")
        {
        }

        public DbSet<Gmail> Emails { get; set; }
    }
}

3. 添加数据库连接字符串

在Web.config的connectionStrings节点下添加:

<add name="EmailDbConnection" 
     connectionString="Data Source=你的SQL服务器名;Initial Catalog=EmailDB;Integrated Security=True;" 
     providerName="System.Data.SqlClient" />

4. 修改控制器添加存储逻辑

在GetAllEmails方法末尾添加数据库存储代码:

// ... 读取邮件并添加到EmailList之后
using (var db = new EmailDbContext())
{
    foreach (var email in EmailList)
    {
        // 避免重复存储同一邮件(根据MsgID判断)
        if (!db.Emails.Any(e => e.MsgID == email.MsgID))
        {
            db.Emails.Add(email);
        }
    }
    db.SaveChanges();
}
return EmailList;

5. 生成数据库

打开Package Manager Console,依次执行:

Enable-Migrations
Add-Migration InitialCreate
Update-Database

执行完成后,系统会自动创建EmailDB数据库及Emails表,读取到的邮件数据会自动存入。

内容的提问来源于stack exchange,提问作者Pallavi Puley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 01:52:51