Search code examples
vb.netemailsmtpgmail

Email not send using Gmail smtp on host


I've used this code to sending emails. When I test this code in LOCALHOST, it works correctly, but in host, I get this error:

Failure sending mail.few

My code is:

Dim MailMsg As New MailMessage(New Net.Mail.MailAddress("[email protected]"), New Net.Mail.MailAddress("[email protected]"))
MailMsg.Subject = "test"
MailMsg.Body = "test"
MailMsg.IsBodyHtml = True
Dim SmtpMail As New Net.Mail.SmtpClient
Dim SMTPUserInfo As New Net.NetworkCredential()
SMTPUserInfo.UserName = "MYUSERNAME"
SMTPUserInfo.Password = "MYPASSWORD"
SmtpMail.UseDefaultCredentials = False
SmtpMail.Credentials = SMTPUserInfo
SmtpMail.Host = "smtp.gmail.com"
SmtpMail.Port = 587
SmtpMail.EnableSsl = True
SmtpMail.Send(MailMsg)

Solution

  •     'Start by creating a mail message object
        Dim MyMailMessage As New MailMessage()
    
        'From requires an instance of the MailAddress type
        MyMailMessage.From = New MailAddress("[email protected]")
    
        'To is a collection of  types
        MyMailMessage.To.Add("[email protected]")
    
        MyMailMessage.Subject = "XXXXXXX" & x
        MyMailMessage.Body = "XXXXXXXXXXXXXXXXXXX "
    
        Dim attach As New Attachment(fileName)
    
        MyMailMessage.Attachments.Add(attach)
    
        'Create the SMTPClient object and specify the SMTP GMail server
        Dim SMTPServer As New SmtpClient("smtp.gmail.com")
        SMTPServer.Port = 587
        SMTPServer.Credentials = New System.Net.NetworkCredential("[email protected]", "PASSWD")
        SMTPServer.EnableSsl = True
        SMTPServer.Send(MyMailMessage)
    
        SMTPServer.Dispose()
    
        MyMailMessage.Dispose()