ASP.Net – Enviando vários anexos

Bem vindos a mais um artigo sobre ASP.Net, hoje estaremos vendo como anexar vários arquivos e enviar e-mail, vamos usar o Gmail, um serviço gratuito de webmail criado pelo Google em 2004, uma de suas principais inovação, é o método com o qual os e-mails recebidos são organizados, denominado “Visualização de Conversas”. Esse método consiste em mostrar todas as mensagens relacionadas com um assunto específico em uma única janela, de uma maneira escalonada, isso é, fica uma mensagem “acima” da outra, conforme a ordem cronológica de envio, e também iremos usar o Plugin Uploadify jQuery. Abaixo esta o HTML. Nada demais, um simple formulário de envio de email.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<table>
<tr><td>Para:</td><td><asp:TextBox ID="txtTo" runat="server"></asp:TextBox></td></tr>
<tr><td>Assunto:</td><td><asp:TextBox ID="txtSubject" runat="server"></asp:TextBox></td></tr>
<tr><td>Mensagem:</td><td><asp:TextBox ID="txtBody" runat="server" TextMode="MultiLine"></asp:TextBox></td></tr>
<tr><td></td><td><asp:FileUpload ID="FileUpload1" runat="server"/></td></tr>
<tr><td></td><td><table id="attachedfiles"></table></td></tr>
<tr><td></td><td><asp:Button ID="btnSend" runat="server" Text="Enviar" OnClick="btnSend_Click"/></td></tr>
</table>

Agora vamos fazer o upload de multiplos arquivos como anexos no email. Para permitir seleccionar e carregar vários arquivos vamos usar o Uploadify jQuery plugin. Baixe o plugin JQuery Uploadify e a Biblioteca JQuery usando os links abaixo. Você também pode acessar outros artigos sobre jQuery na seção de desenvolvimento.

Download JQuery

Download Uploadify

Uma vez baixado, você precisará colocar dos quatro arquivos jquery-1.3.2.min.js,  jquery.uploadify.js,uploader.fla e uploader.swf em uma pasta chamada scripts na pasta raiz do seu aplicativo Web site ASP.Net

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
<link rel="Stylesheet" type="text/css" href="CSS/uploadify.css" />
<script type="text/javascript" src="scripts/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="scripts/jquery.uploadify.js"></script>
<script type="text/javascript">
$(function () {
$("[id*=FileUpload1]").fileUpload({
'uploader': 'scripts/uploader.swf',
'cancelImg': 'images/cancel.png',
'buttonText': 'Attach Files',
'script': 'Upload.ashx',
'folder': 'uploads',
'multi': true,
'auto': true,
'onSelect': function (event, ID, file) {
$("#attachedfiles tr").each(function () {
if ($("td", this).eq(0).html() == file.name) {
alert(file.name + " já carregado.");
$("[id*=FileUpload1]").fileUploadCancel(ID);
return;
}
});
},
'onComplete': function (event, ID, file, response, data) {
$("#attachedfiles").append("<tr><td>" + file.name + "</td><td><a href = 'javascript:;'>[x]</a></td></tr>");
}
});
});
</script>

Os arquivos são enviados via Generic Handler Upload.ashx. Vamos armazenar os arquivos carregados em sessão. Além disso, os arquivos enviados são exibidos dinamicamente na página.

C#

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
<%@ WebHandler Language="C#" %>
using System;
using System.Web;
using System.IO;
using System.Web.SessionState;
using System.Collections.Generic;
public class UploadCS : IHttpHandler, IRequiresSessionState {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
context.Response.Expires = -1;
try
{
List<HttpPostedFile> files = (List<HttpPostedFile>)context.Session["Files"];
HttpPostedFile postedFile = context.Request.Files["Filedata"];
files.Add(postedFile);
string filename = postedFile.FileName;
context.Response.Write(filename);
context.Response.StatusCode = 200;
}
catch (Exception ex)
{
context.Response.Write("Erro: " + ex.Message);
}
}
&nbsp;
public bool IsReusable {
get {
return false;
}
}
}

VB.Net

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
<%@ WebHandler Language="VB" %>
Imports System
Imports System.Web
Imports System.IO
Imports System.Collections.Generic
&nbsp;
Public Class UploadVB : Implements IHttpHandler, IRequiresSessionState
&nbsp;
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Try
Dim files As List(Of HttpPostedFile) = DirectCast(context.Session("Files"), List(Of HttpPostedFile))
Dim postedFile As HttpPostedFile = context.Request.Files("Filedata")
files.Add(postedFile)
Dim filename As String = postedFile.FileName
context.Response.Write(filename)
context.Response.StatusCode = 200
Catch ex As Exception
context.Response.Write("Erro: " + ex.Message)
End Try
End Sub
&nbsp;
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
&nbsp;
End Class

Será preciso remover os arquivos anexados usando jQuery AJAX, para isso vamos acrescentar a funcionalidade para remover arquivos que temos no navegador e vamos recorrer ao uso do jQuery AJAX e ASP.Net Page Methods.

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
<script type="text/javascript">
$("#attachedfiles a").live("click", function () {
var row = $(this).closest("tr");
var fileName = $("td", row).eq(0).html();
$.ajax({
type: "POST",
url: "Default.aspx/RemoveFile",
data: '{fileName: "' + fileName + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () { },
failure: function (response) {
alert(response.d);
}
});
row.remove();
});
</script>

A função JavaScript acima faz a chamada para um WebMethod definido abaixo, que exclui o arquivo da variável de sessão onde estava armazenado.

C#

 

1
2
3
4
5
6
7
8
9
10
11
[WebMethod]
public static void RemoveFile(string fileName)
{
List<HttpPostedFile> files = (List<HttpPostedFile>)HttpContext.Current.Session["Files"];
files.RemoveAll(f => f.FileName.ToLower().EndsWith(fileName.ToLower()));
}

 

VB.Net

 

1
2
3
4
5
6
7
8
9
<WebMethod()> _
Public Shared Sub RemoveFile(fileName As String)
Dim files As List(Of HttpPostedFile) = DirectCast(HttpContext.Current.Session("Files"), List(Of HttpPostedFile))
files.RemoveAll(Function(f) f.FileName.ToLower().EndsWith(fileName.ToLower()))
End Sub

E vamos enviar o e-mail com múltiplos anexos, finalmente aqui está o código para enviar e-mail usando a conta do GMAIL.

C#

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
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["Files"] = new List<HttpPostedFile>();
}
}
&nbsp;
protected void btnSend_Click(object sender, EventArgs e)
{
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.From = new MailAddress("user@gmail.com");
mailMessage.Subject = txtSubject.Text.Trim();
mailMessage.Body = txtBody.Text.Trim();
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MailAddress(txtTo.Text.Trim()));
List<HttpPostedFile> files = (List<HttpPostedFile>)Session["Files"];
foreach (HttpPostedFile file in files)
{
mailMessage.Attachments.Add(new Attachment(file.InputStream, Path.GetFileName(file.FileName), file.ContentType));
}
&nbsp;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = mailMessage.From.Address;
NetworkCred.Password = "<Password>";
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mailMessage);
}
Response.Redirect(Request.Url.AbsoluteUri);
}

VB.Net

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
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
Session("Files") = New List(Of HttpPostedFile)
End If
End Sub
&nbsp;
Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim mailMessage As MailMessage = New MailMessage
mailMessage.From = New MailAddress("user@gmail.com")
mailMessage.Subject = txtSubject.Text.Trim
mailMessage.Body = txtBody.Text.Trim
mailMessage.IsBodyHtml = True
mailMessage.To.Add(New MailAddress(txtTo.Text.Trim))
Dim files As List(Of HttpPostedFile) = CType(Session("Files"), List(Of HttpPostedFile))
For Each file As HttpPostedFile In files
mailMessage.Attachments.Add(New Attachment(file.InputStream, Path.GetFileName(file.FileName), file.ContentType))
Next
Dim smtp As SmtpClient = New SmtpClient
smtp.Host = "smtp.gmail.com"
smtp.EnableSsl = True
Dim NetworkCred As System.Net.NetworkCredential = New System.Net.NetworkCredential
NetworkCred.UserName = mailMessage.From.Address
NetworkCred.Password = "<Password>"
smtp.UseDefaultCredentials = True
smtp.Credentials = NetworkCred
smtp.Port = 587
smtp.Send(mailMessage)
Response.Redirect(Request.Url.AbsoluteUri)
End Sub

Deixe um comentário