How to send email with attachment in Xamarin.android?

0

I am developing an App in Xamarin for android which generates a PDF that is saved in a hidden folder of the device.

I currently use a WebService to send the email but it does not arrive with the attached PDF.
I'm using a WebService because I need this email to be sent automatically without any interaction with the user and the examples I had found on the internet usually opened gmail or another dialog which asked the user to send the email.

The exception that debug me back is:

  

System.IO.IOException: The network path was not found.

Obviously this exception occurs because the WS will pass the location (on the device) of the PDF as an argument and the WS can not find that file since the received location does not exist on the server where the WS is located.

My question is How can I pass the PDF to the WebService and send the attachment?

I leave here the code that I use to send the mail:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Web;

namespace Servicios.Clases
{
    public class cmSendMailCcopy
    {
        public string mailTo;
        public string mailCopy;
        public string mailFrom;
        public string mailSubject;
        public string mailBody;
        public string mailAuthentication;
        public string mailPassword;
        public string mailSmtpServer;

        public void Send(string mailTo, string mailCopy, string mailFromAddress, string mailFromName,
                     string mailSubject, string mailBody, string mailAuthentication, string mailPassword,
                     string mailSmtpServer, int mailPort, List<string> mailAttachment = null)
        {
            try
            {
                MailMessage mail = new MailMessage();

                string mailDe = mailFromAddress;
                string deNombre = mailFromName;
                string mailPara = mailTo;
                string mailCopia = mailCopy;
                string asunto = mailSubject;
                string mensaje = mailBody;
                string mailAutenticacion = mailAuthentication;
                string mailContra = mailPassword;
                string mailSmtp = mailSmtpServer;
                int mailPuerto = mailPort;
                List<string> mailAdjunto = mailAttachment;

                try
                {
                    SmtpClient smtp = new SmtpClient
                    {
                        Host = mailSmtp,
                        Port = mailPuerto,
                        EnableSsl = false,
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        Credentials = new NetworkCredential(mailDe, mailContra),
                        Timeout = 3000
                    };

                    MailMessage correo = new MailMessage(mailDe, mailPara, asunto, mensaje);
                    correo.IsBodyHtml = true;
                    correo.CC.Add(mailCopia);

                    if (mailAdjunto != null){
                        foreach (var item in mailAdjunto)
                        {
                            if (System.IO.File.Exists(item)){
                                correo.Attachments.Add(new Attachment(item, MediaTypeNames.Application.Pdf));
                            }
                        }
                    }
                    smtp.Send(correo);
                }
                catch (Exception)
                {
                    throw;
                }
            }
            catch (Exception exc)
            {
                throw (exc);
            }
        }
    }
}
    
asked by Matias 20.09.2018 в 15:45
source

1 answer

0

I found the solution to the problem, I will detail it in the following steps:

1- The last argument you receive is a List<string> , instead it should be List<byte[]>

2- Before calling the WebService, you have to convert the PDF into byte [], for that we do the following:

//Creamos una List<byte[]>
List<byte[]> adjuntos = new List<byte[]>();
//Definimos un array de tipo byte el cual va a contener los bytes del PDF
byte[] adjArreglo = File.ReadAllBytes(pdfAdjunto);
//Agregamos los bytes del PDF a la Lista
adjuntos.Add(adjArreglo);

3- In the program that sends the mail, there is a statement if (mailAdjunto != null) , within this if we put the following:

//Recorremos toda la Lista
foreach (var item in mailAdjunto)
{
    Por cada elemento de la lista, convertimos los byte[] en Stream
    Stream str = new MemoryStream(item);
    //Llamamos al Attachments.Add() con el steam, el nombre que tiene el PDF y el tipo de archivo (en este caso PDF)
    correo.Attachments.Add(new Attachment(str, "Test.pdf", MediaTypeNames.Application.Pdf));
}

This sends the email with the attached PDF.
Step 3 can be done directly without the Stream, but in the mail instead of showing "Test.pdf" the name of the attached file will be called as the entire path of where the pdf is stored.

    
answered by 20.09.2018 / 21:43
source