Отправить страницу по электронной почте ViewState проблема - PullRequest
1 голос
/ 17 декабря 2009

Мой клиент хочет страницу, которую он может отправить как электронное письмо через IE, но когда я делаю Файл> Отправить> Страница по электронной почте, он добавляет скрытое поле ввода вверху страницы с некоторыми случайными буквами.

Меня попросили удалить его ...

Я попробовал EnableViewState = false и удалил его из dom с помощью javascript и даже скрыл его с помощью CSS, но он по-прежнему отображается в электронном письме (но не на странице в браузере) :(

Я не знаю, что вам, возможно, понадобится, чтобы помочь, поэтому я вставлю все это, вот кодировки:

CS:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WorksUnit.Clydesdale.PropertyManager;
using WorksUnit.Clydesdale.PropertyManager.BusinessObjects;

namespace WorksUnit.Clydesdale.PropertyManager.Website.Summary
{
    public partial class MaintenanceJobSheet : System.Web.UI.Page
    {
        private int _cachedPropertyId = 0;
        private const string PROPERTYID_QUERY_STRING = "PropertyID";
        private int _propertyId
        {
            get
            {
                if (_cachedPropertyId == 0 && Request.QueryString[PROPERTYID_QUERY_STRING] != null)
                {
                    int.TryParse(Request.QueryString[PROPERTYID_QUERY_STRING].ToString(), out _cachedPropertyId);
                }

                return _cachedPropertyId;
            }
            set { _cachedPropertyId = value; }
        }
        private int maintenanceId
        {
            get
            {
                if (!string.IsNullOrEmpty(Request.QueryString["maintenanceId"]))
                {
                    return Convert.ToInt32(Request.QueryString["maintenanceId"]);
                }
                else
                {
                    return 0;
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (maintenanceId != 0)
            {
                BusinessObjects.Maintenance maintenance = BusinessObjects.Maintenance.Retrieve(maintenanceId);
                LiteralJobNumber.Text = maintenance.JobNumber;
                LiteralDescription.Text = maintenance.Description;
                LiteralContractor.Text = maintenance.Contractor.Description;
                if(maintenance.Date!=DateTime.MinValue)
                {
                    LiteralDate.Text = maintenance.Date.ToShortDateString();
                }
                if(maintenance.CompletionDate!=DateTime.MinValue)
                {
                    LiteralCompletionDate.Text = maintenance.CompletionDate.ToShortDateString();
                }
                if(maintenance.DateInvoiced!=DateTime.MinValue)
                {
                    LiteralInvoicedDate.Text = maintenance.DateInvoiced.ToShortDateString();
                }
                if(maintenance.DatePaid!=DateTime.MinValue)
                {
                    LiteralDatePaid.Text =maintenance.DatePaid.ToShortDateString();
                }
                LiteralChargeDetails.Text = maintenance.DetailsOfCharging;
                LiteralUpdate.Text = maintenance.LatestSummary;
            }
        }
    }
}

интерфейс:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MaintenanceJobSheet.aspx.cs" EnableViewState="false" Inherits="WorksUnit.Clydesdale.PropertyManager.Website.Summary.MaintenanceJobSheet" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Clydesdale Property Solutions Work Request</title>
    <link rel="stylesheet" type="text/css" media="screen" href="/css/screen.css" />
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <span><b>Contractor:</b>&nbsp;&nbsp;</span><asp:Literal ID="LiteralContractor" runat="server" />
        <br /><br />
        <span>Please undertake the following:-</span>
        <br /><br />
        <table width="600" cellpadding="3" cellspacing="0" border="1px">
        <tr>
            <td valign="top" width="150">Job Number:</td>            
            <td><asp:Literal ID="LiteralJobNumber" runat="server" Text="N/A" /></td>
        </tr>
        <tr>
            <td valign="top" width="150">Description:</td>            
            <td><asp:Literal ID="LiteralDescription" runat="server" /></td>
        </tr>
        <tr>
            <td valign="top" width="150">Date:</td>            
            <td><asp:Literal ID="LiteralDate" runat="server" /></td>
        </tr>
        <tr>
            <td valign="top" width="150">Completion Date:</td>
            <td><asp:Literal ID="LiteralCompletionDate" runat="server" /></td>
        </tr>        
        <tr>
            <td valign="top" width="150">Invoiced Date:</td>
            <td><asp:Literal ID="LiteralInvoicedDate" runat="server" /></td>
        </tr>
        <tr>
            <td valign="top" width="150">Date Paid:</td>
            <td><asp:Literal ID="LiteralDatePaid" runat="server" /></td>
        </tr>
        <tr>
            <td valign="top" width="150">Details of Charging:</td>
            <td><asp:Literal ID="LiteralChargeDetails" runat="server" /></td>
        </tr>
        <tr>
            <td valign="top" width="150">Update:</td>
            <td><asp:Literal ID="LiteralUpdate" runat="server" /></td>
        </tr>
        </table>
        <br /><br /><br />
        <span>Thank You</span>
        <br /><br /><br />
        Clydesdale Estates,<br />
        Tel:02380331234 <br />
        Fax:02380335522<br />
        Email: info@clydesdale-estates.co.uk
    </div>
    </form>
</body>
</html>

И это то, что показывает, когда я Просмотр источника на электронную почту:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Clydesdale Property Solutions Work Request</TITLE>
<META content="text/html; charset=iso-8859-1" http-equiv=Content-Type>
<BASE href="http://localhost:4659/Summary/MaintenanceJobSheet.aspx">
<LINK rel=stylesheet type=text/css href="/css/screen.css" media=screen>
<META name=GENERATOR content="MSHTML 8.00.6001.18854">
</HEAD>
<BODY>
<FORM id=form1 method=post name=form1 action=MaintenanceJobSheet.aspx>
<!-- random input appears here (wrapped in a div) --><DIV>
<INPUT id=__VIEWSTATE 
value=/wEPDwUJNzAyODg3NjY4ZGT+zJss/Xlbkhlxv8we8oRPUGNy9Q== type=hidden name=__VIEWSTATE> 
</DIV> <!-- and ends here -->
<DIV><SPAN><B>Contractor:</B>&nbsp;&nbsp;</SPAN> <BR><BR><SPAN>Please undertake the following:-</SPAN> <BR><BR>
<TABLE border=1 cellSpacing=0 cellPadding=3 width=600>
<TD vAlign=top width=150><!-- more content goes here --></TD>
</TR>
</TABLE>
</DIV>
</FORM>
</BODY>
</HTML>

Любая помощь будет принята с благодарностью.

1 Ответ

0 голосов
/ 17 декабря 2009

У меня была похожая проблема, я создаю новостное письмо в формате HTML для своего работодателя, и весь внутренний код (картинки, ссылки ...) изменяется при отправке через Internet Exploder / Outlook.

Я уверен, что ваш клиент (как и мой) хочет эту функцию, чтобы они могли использовать свой внешний вид для редактирования электронных писем и отправлять их своим контактам внешнего вида. Кажется, способов обойти это не так много.

Пока я нашел только два пути.

  1. Вы можете использовать другой почтовый клиент (например, Thunderbird от Mozilla). Вы можете скопировать и вставить исходный код в исходное сообщение электронной почты и отправить его (хотя на самом деле это не совсем профессиональный проект, когда вы копируете и вставляете кого-то другого).

  2. Или другой способ заключается в том, что вы можете создать свой собственный почтовый сервис, используя библиотеки на других языках. Например, PHP.

    Когда вы отправляете вещи через PHP, ничего не меняется, и вы контролируете, с какого электронного письма оно пришло. Требуется немного доработать, чтобы письма не отбрасывались как спам, но я разместил код ниже, если вам интересно.

Если у кого-то есть идея получше или более простой способ сделать это, пожалуйста, дайте мне знать, что я был бы очень рад, если бы существовал более простой способ.
Вы должны почти сказать, винт это и оставить его как есть.

<?php 
//file_get_contents('./newsletter.html', true); // or use a file for the body
//$body = file_get_contents('../newsletter/2010/1/newsletter.html', true);
//define the receiver of the email
$to = 'someone@receiver.com';
//define the subject of the email
$subject = 'Test HTML email'; 
//create a boundary string. It must be unique 
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time())); 
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: you@yourEmail.com\r\nReply-To: you@yourEmail.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/alternative; boundary=\"PHP-alt-".$random_hash."\""; 
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-alt-<?php echo $random_hash; ?>  
Content-Type: text/plain; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit

Hello World!!! 
This is simple text email message. 

--PHP-alt-<?php echo $random_hash; ?>  
Content-Type: text/html; charset="iso-8859-1" 
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>
<img src="http://****/test.png" width="600" height="123" alt="test pic for html email">

--PHP-alt-<?php echo $random_hash; ?>--
<?
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed" 
echo $mail_sent ? "Mail sent" : "Mail failed";
?>
...