envio mail

ButterflyEffect

Power Member
boa tarde. precisava de fazer algo dest genero e encontrei o codigo e adaptei-o mas da-me este erro.podiam ajudarm?
cumps


erro
F:\liz.txtNumber of attachments are1Ocorreu uma falha na ligação do transporte ao servidor.

codigo
Código:
protected void Page_Load(object sender, System.EventArgs e)
  {
   if(!Page.IsPostBack) 
   {
 
   }
  }
  #region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: This call is required by the ASP.NET Web Form Designer.
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  /// <summary>
  /// Required method for Designer support - do not modify
  /// the contents of this method with the code editor.
  /// </summary>
  private void InitializeComponent()
  {    
  }
  #endregion
  // button used to send the email
  protected void Button1_Click(object sender, System.EventArgs e)
  {
           MailMessage mail = new MailMessage(); 
   mail.To = txtTo.Text; 
   mail.From = txtFrom.Text; 
   mail.Subject = txtSubject.Text; 
   mail.Body = txtBody.Text; 
   
   MailAttachment attachment = null; 
   
   try 
   {
    // check to see if there are any attachments or not
    if(FileList.Items.Count > 0) 
    {
     
     foreach(ListItem l in FileList.Items)
     {
      // Attaches a new attachment contained in the List
      Response.Write(l.Text);
      attachment = new MailAttachment(l.Text); 
      mail.Attachments.Add(attachment);
      
     }
          
    }
                   
    //mail.Attachments.Add(attachment); 
    Response.Write("Number of attachments are"+mail.Attachments.Count); 
   
    SmtpMail.SmtpServer = "localhost"; 
    SmtpMail.Send(mail); 
   }
   catch(Exception ex) 
   {
    Response.Write(ex.Message); 
    
    // Cacthes the exception here 
   }
  }
  // Button used to attach a file 
  protected void Button2_Click(object sender, System.EventArgs e)
  {
   // gets the file name with the whole path
   string attachedFile =  File1.PostedFile.FileName;   
               
   // Adds the item in the list of attached files 
   if(attachedFile != "") 
   {
    FileList.Items.Add(attachedFile); 
   }
 
  }
 }
}
 
Última edição pelo moderador:
Código:
    SmtpMail.SmtpServer = "localhost";

Tens 1 smtp server no teu pc?

Para enviar por smtp tens k fazer login no serv, e duvido k tenhas no teu pc e sendo assim devias usar um publico.

Eu posso-te ajudar, já k fiz uma especie de email cliente em java à 1s tempos
 
para colocar a funcioonar alem d SmtpMail.SmtpServer = "localhost"; que ja tenho e continua a dar erro. tenho de criar alguma conta de email ou axim?
podiam explicar mais ou menos o que é necessario alem d servidor?
cumps e obrigada
 
Agora fiquei curioso: como é que se manda um mail sem utilizar um servidor smtp (local ou remoto)? UUCP?
como se fosse um browser, vais la com posts e gets :p
Dá mt + trabalho e é mt instavel (por ex no gmail o formulário já foi varias vezes alterado)
Ainda deve dar por UCP mas so sabendo o protocolo smtp para saber como é k ele enviaria.


para colocar a funcioonar alem d SmtpMail.SmtpServer = "localhost"; que ja tenho e continua a dar erro. tenho de criar alguma conta de email ou axim?
podiam explicar mais ou menos o que é necessario alem d servidor?
cumps e obrigada
Dá pra fazer sem ter conta no servidor, mas penso k depende do servidor. (Já n me lembro, já lá vai 1 tempinho k n pego nisto)

mas aki vai 1 exemplo:
Código:
import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
 
public class EmailAttachmentDemo {
    public static void main(String[] args) {
        EmailAttachmentDemo demo = new EmailAttachmentDemo();
        demo.sendEmail();
    }
    
    public void sendEmail() {
        String from = "me@host";
        String to = "me@host";
        String subject = "Important Message";
        String bodyText = "This is a important message with attachment";
        String filename = "message.pdf";
        
        Properties properties = new Properties();
        properties.put("mail.stmp.host", "host"); // exemplo: host= "smtp.gmail.com"
        properties.put("mail.smtp.port", "25");
        Session session = Session.getDefaultInstance(properties, null);
        
        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);
            message.setSentDate(new Date());
            
            //
            // Set the email message text.
            //
            MimeBodyPart messagePart = new MimeBodyPart();
            messagePart.setText(bodyText);
            
            //
            // Set the email attachment file
            //
            MimeBodyPart attachmentPart = new MimeBodyPart();
            FileDataSource fileDataSource = new FileDataSource(filename) {
                @Override
                public String getContentType() {
                    return "application/octet-stream";
                }
            };
            attachmentPart.setDataHandler(new DataHandler(fileDataSource));
            attachmentPart.setFileName(filename);
            
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messagePart);
            multipart.addBodyPart(attachmentPart);
            
            message.setContent(multipart);
            
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}

Aconselho-te a usar a lib da apache, é mt boa, eles tem la exemplos (no exmplo acima n é utilizada)
http://commons.apache.org/email/

Toma nota que alguns servidores como o Gmail usam ssl
entao tens k por nas properties k usa ssl:
Código:
if (ssl) {
         properties.put("mail.smtp.starttls.enable","true"); //faz enable do ssl
         properties.put( "mail.smtp.quitwait", "false" ); // não desliga quando o servidor manda esperar
         System.setProperties(props );
}

Se tiver k usar autenticação no servidorfica assim (este era parte do meu codigo k ainda encontrei aki, usando a lib da apache)
Código:
 import org.apache.commons.mail.MultiPartEmail;
 MultiPartEmail email = new MultiPartEmail();
 if (ssl) {
    Properties properties =System.getProperties();
    properties.put("mail.smtp.starttls.enable","true");
    properties.put( "mail.smtp.quitwait", "false" );
    System.setProperties(properties );
 }
 email.setHostName(smtpServer);
 email.setAuthentication(login, senha);
// (...)
 
Última edição:
Back
Topo