working on it ...

Filters

Explore Public Snippets

Sort by

Found 840 snippets matching: smtp+

    public by JackLatanis modified Nov 3, 2014  297764  6  6  -1

    Sending email via AuthMailer service using PHP

    //this code sends emails via AuthMailer service (www.authmailer.com)
    
    <?
    
    //install the Mail, Net_Socket and Net_SMTP with PEAR
    require_once "Mail.php";
     
    //mail headers and body
    $from = "Me";
    $to = "You";
    $subject = "Subject";
    $body = "Lorem Ipsum...";
    
    //server configuration, edit with your account details 
    $host = "authmailer.com";
    $port = "587";
    $user = "user";
    $pass = "pass";
     
    $headers = array('From' => $from,
    	'To' => $to,
    	'Subject' => $subject);
    
    $smtp = Mail::factory('smtp',
    	array('host' => $host,
    	'auth' => true,
    	'username' => $user,
    	'password' => $pass));
    
    //sending email
    $mail = $smtp->send($to, $headers, $body);
     
    if (PEAR::isError($mail)) 
    {
      //something went wrong
    	echo($mail->getMessage());
    } 
    else 
    {
      //OK
    	echo("Message was sent!");
    }
    
    ?>

    public by cghersi @ MailUp API DEV modified Aug 29, 2018  1675  46  5  0

    MailUp REST API - How to send a transactional email message

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server. The credentials of the SMTP+ user are passed as parameter in the body of the request. Explore the MessageDTO object in order to understand how you can customize the message you want to send.
    public static void SendMessage()
    {
      // 1) Required values
      string username = "<your_username>";
    	string password = "<your_password>";
    
    	string clientid = "<your_clientid>";
    	string clientsecret = "<your_clientsecret>";
    
    	string smtpplus_username = "<your_smtpplus_username>";
    	string smtpplus_password = "<your_smtpplus_password>";
      
      // 2) Setup the MailUp Client:
    	MailUpClient client = new MailUpClient(clientid, clientsecret);
    	client.RetrieveAccessToken( username, password );
    
      // 3) prepare the input:
      MessageDTO msg = new MessageDTO()
      {
        Html = new HtmlDTO()
        {
          Body = "<div>Hello Mr. [firstname][lastname] !!!</div><br><img width='600' height='397' src='cid:img001'>",
          BodyTag = "<body>"
        },
        Text = "Hello world!!!",
        Subject = "Hello friend!",
        From = new EmailAddressDTO() { Name = "Test User", Email = "test@mailup.it" },
        To = new List<EmailAddressDTO>() { new EmailAddressDTO() { Name = "Massimo", Email = "info@mailup.it" } },
        Cc = new List<EmailAddressDTO>(),
        Bcc = new List<EmailAddressDTO>(),
        ReplyTo = null,
        CharSet = "utf-8",
        ExtendedHeaders = null,
        Attachments = null,
        EmbeddedImages = new List<MessagePartDTO>() {
          new MessagePartDTO() {
            Filename = "Image.jpg",
            ContentId = "img001",
            Body = new byte[] { 0x01, 0x02, 0x03, 0x04 }
          }
        },
        XSmtpAPI = new XSmtpAPIDTO()
        {
          CampaignName = "Test Campaign",
          CampaignCode = "1001",
          Header = null,
          Footer = null,
          ClickTracking = null,
          ViewTracking = null,
          Priority = null,
          Schedule = null,
          DynamicFields = new List<NameValueDTO>() {
            new NameValueDTO() { N = "firstname", V = "Mario"},
            new NameValueDTO() { N = "lastname", V = "Rossi"}
          },
          CampaignReport = null,
          SkipDynamicFields = null
        },
        User = new SmtpUserDTO() { Username = smtpplus_username, Secret = smtpplus_password }
      };
    
      // 4) Invoke the web method:
      SendResponseDTO result = null;
      try
      {
        result = client.SendMessage(msg);
      }
      catch (Exception ex)
      {
        Console.WriteLine("Cannot perform the operation due to " + ex.Message);
        return;
      }
    
      // 5) Print results:
      if (result != null)
        Console.WriteLine("Result of sending task:" + result.Message);
      else
        Console.WriteLine("An error occurred while sending message.");
    }
    						

    public by cghersi @ MailUp API DEV modified Aug 29, 2018  2232  12  5  0

    MailUp REST API - How to send a transactional email message that follows a template

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server. The credentials of the SMTP+ user are passed as parameter in the body of the request. Explore the TemplateDTO object in order to understand how you can customize the message you want to send.
    public static void SendTemplate()
    {
      // 1) Required values
      string username = "<your_username>";
    	string password = "<your_password>";
    
    	string clientid = "<your_clientid>";
    	string clientsecret = "<your_clientsecret>";
    
    	string smtpplus_username = "<your_smtpplus_username>";
    	string smtpplus_password = "<your_smtpplus_password>";
      
      // 2) Setup the MailUp Client:
    	MailUpClient client = new MailUpClient(clientid, clientsecret);
    	client.RetrieveAccessToken( username, password );
    
      // 3) prepare the input:
      TemplateDTO msg = new TemplateDTO()
      {
        TemplateId = 694,
        Subject = "Test message from template",
        From = new EmailAddressDTO() { Name = "Test User", Email = "test@mailup.it" },
        To = new List<EmailAddressDTO>() { new EmailAddressDTO() { Name = "Massimo", Email = "info@mailup.it" } },
        Cc = new List<EmailAddressDTO>(),
        Bcc = new List<EmailAddressDTO>(),
        ReplyTo = null,
        CharSet = "utf-8",
        ExtendedHeaders = null,
        Attachments = null,
        EmbeddedImages = new List<MessagePartDTO>() {
          new MessagePartDTO() {
            Filename = "Image.jpg",
            ContentId = "img001",
            Body = new byte[] { 0x01, 0x02, 0x03, 0x04 }
          }
        },
        XSmtpAPI = null,
        User = new SmtpUserDTO() { Username = smtpplus_username, Secret = smtpplus_password }
      };
    
      // 4) Invoke the web method:
      SendResponseDTO result = null;
      try
      {
        result = client.SendTemplate(msg);
      }
      catch (Exception ex)
      {
        Console.WriteLine("Cannot perform the operation due to " + ex.Message);
        return;
      }
    
      // 5) Print results:
      if (result != null)
        Console.WriteLine("Result of sending task:" + result.Message);
      else
        Console.WriteLine("An error occurred while sending template.");
    }
    												

    public by cghersi @ MailUp API DEV modified Aug 29, 2018  1749  8  5  0

    MailUp REST API - How to retrieve information of SMTP+ Users

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server. The credentials of the SMTP+ user are passed as parameter in the body of the request. You can optionally specify a username as third parameter in order to filter the resulting list.
    public static void GetUserInfo()
    {
      // 1) Required values
      string username = "<your_username>";
    	string password = "<your_password>";
    
    	string clientid = "<your_clientid>";
    	string clientsecret = "<your_clientsecret>";
    
    	string smtpplus_username = "<your_smtpplus_username>";
    	string smtpplus_password = "<your_smtpplus_password>";
      
      // 2) Setup the MailUp Client:
    	MailUpClient client = new MailUpClient(clientid, clientsecret);
    	client.RetrieveAccessToken( username, password );
    
      // 3) Invoke the web method:
      List<UserInfoDTO> result = null;
      try
      {
        result = client.ListUserInfo(smtpplus_username, smtpplus_password);
      }
      catch (Exception ex)
      {
        Console.WriteLine("Cannot perform the operation due to " + ex.Message);
        return;
      }
    
      // 4) Print results:
      if (result != null)
        Console.WriteLine("Retrieved users total:" + result.Count);
      else
        Console.WriteLine("An error occurred while retrieving users.");
    }
    																		

    public by Mk47 modified Feb 4, 2014  2653  3  5  2

    Sending multiple email using Java ( Using Gmail SMTP )

    import java.util.Properties;
    
    import javax.mail.Message;
    import javax.mail.MessagingException;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.AddressException;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeMessage;
    
    public class JavaEmail
    {
        Session mailSession;
    
        public static void main(String args[]) throws AddressException,    MessagingException
        {
            JavaEmail javaEmail = new JavaEmail();
            javaEmail.setMailServerProperties();
            javaEmail.draftEmailMessage();
            javaEmail.sendEmail();
        }
    
        private void setMailServerProperties()
        {
            Properties emailProperties = System.getProperties();
            emailProperties.put("mail.smtp.port", "587");
            emailProperties.put("mail.smtp.auth", "true");
            emailProperties.put("mail.smtp.starttls.enable", "true");
            mailSession = Session.getDefaultInstance(emailProperties, null);
        }
    
        private MimeMessage draftEmailMessage() throws AddressException, MessagingException
        {
            String[] toEmails = { "Google@gmail.com" };
            String emailSubject = "Test email subject";
            String emailBody = "This is a test message";
            MimeMessage emailMessage = new MimeMessage(mailSession);
            /**
             * Set the mail recipients
             * */
            for (int i = 0; i < toEmails.length; i++)
            {
                emailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmails[i]));
            }
            emailMessage.setSubject(emailSubject);
            /**
             * If sending HTML mail
             * */
            emailMessage.setContent(emailBody, "text/html");
            /**
             * If sending only text mail
             * */
            //emailMessage.setText(emailBody);// for a text email
            return emailMessage;
        }
    
        private void sendEmail() throws AddressException, MessagingException
        {
            /**
             * Sender's credentials
             * */
            String fromUser = "user-email@gmail.com";
            String fromUserEmailPassword = "*******";
    
            String emailHost = "smtp.gmail.com";
            Transport transport = mailSession.getTransport("smtp");
            transport.connect(emailHost, fromUser, fromUserEmailPassword);
            /**
             * Draft the message
             * */
            MimeMessage emailMessage = draftEmailMessage();
            /**
             * Send the mail
             * */
            transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
            transport.close();
            System.out.println("Email sent successfully.");
        }
    }  

    public by sherazkhan modified Nov 11, 2015  2259  1  6  0

    How to Send Email Messages using DNS inside C# & VB.NET Apps

    This technical tip explains how to send an email messages using DNS inside .NET applications. Sometimes sending mails using an SMTP server is not feasible for a project’s requirement. We may want to utilize the MX record of the recipient’s domain name.
    // Enter here the actual content of the snippet.            
    static void Main(string[] args)
    {
        try
        {
            MailMessage msg = new MailMessage("add1@domain.com", "add1@domain.com", "test", "this is a test");
            msg.CC.Add(new MailAddress("add2@domain.com", "CC Display Name"));
            DnsSendMessage(msg);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    
        Console.WriteLine("Program finished. Press any key to exit....");
        Console.ReadKey();
    }
    
    /// <summary>
    /// Use for sent message
    /// </summary>
    /// <param name="msg">message to send</param>
    /// <returns></returns>
    private static void DnsSendMessage(MailMessage msg)
    {
        // Get all the recipients in to, cc and bcc in one collection
        MailAddressCollection addresses = new MailAddressCollection();
        foreach (MailAddress to in msg.To)
        {
            addresses.Add(to);
        }
        foreach (MailAddress cc in msg.CC)
        {
            addresses.Add(cc);
        }
        foreach (MailAddress bcc in msg.Bcc)
        {
            addresses.Add(bcc);
        }
    
        // send mail using DNS to each address
        foreach (MailAddress addr in addresses)
        {
            //Find mail exchange servers with the help of DnsClient
            DnsClient dnsClient = new DnsClient();
            Question mxQuestion = new Question(addr.Host, QueryType.MX);
            if (dnsClient.Resolve(mxQuestion))
            {
                // try to send a message
                foreach (ResourceRecord record in dnsClient.ReceivedMessage.Answers)
                {
                    MXResourceRecord cnRecord = record as MXResourceRecord;
                    if (cnRecord != null)
                    {
                        try
                        {
                            // Send message
                            SmtpClient client = new SmtpClient();
                            client.AuthenticationMethod = SmtpAuthentication.None;
                            client.Host = cnRecord.ExchangeName;
                            client.Port = 25;
                            client.Send(msg);
                            Console.WriteLine("Mail sent to " + addr.Address);
                        }
                        catch (SmtpException e)
                        {
                            Console.WriteLine(cnRecord.ExchangeName + ": " + e.Message + Environment.NewLine);
                            continue;
                        }
                    }
                }
            }
        }
    }
    

    public by msdn modified Jan 12, 2015  84990  2  5  0

    SendTaskCore: The core implementation of SendTask.

    The core implementation of SendTask. The client. The user-supplied state. A delegate that initiates the asynchronous send. The provided TaskCompletionSource must be passed as the user-supplied state to the actual SmtpClient.SendAsync method.
    using System.Net.Mail;
    using System.Threading.Tasks;
    
    /// <summary>The core implementation of SendTask.</summary>
    /// <param name="smtpClient">The client.</param>
    /// <param name="userToken">The user-supplied state.</param>
    /// <param name="sendAsync">
    /// A delegate that initiates the asynchronous send.
    /// The provided TaskCompletionSource must be passed as the user-supplied state to the actual SmtpClient.SendAsync method.
    /// </param>
    /// <returns></returns>
    private static Task SendTaskCore(SmtpClient smtpClient, object userToken, Action<TaskCompletionSource<object>> sendAsync)
    {
        // Validate we're being used with a real smtpClient.  The rest of the arg validation
        // will happen in the call to sendAsync.
        if (smtpClient == null) throw new ArgumentNullException("smtpClient");
    
        // Create a TaskCompletionSource to represent the operation
         var tcs = new TaskCompletionSource<object>(userToken);
    
        // Register a handler that will transfer completion results to the TCS Task
        SendCompletedEventHandler handler = null;
        handler = (sender, e) => EAPCommon.HandleCompletion(tcs, e, () => null, () => smtpClient.SendCompleted -= handler);
        smtpClient.SendCompleted += handler;
    
        // Try to start the async operation.  If starting it fails (due to parameter validation)
        // unregister the handler before allowing the exception to propagate.
        try
        {
            sendAsync(tcs);
        }
        catch(Exception exc)
        {
            smtpClient.SendCompleted -= handler;
            tcs.TrySetException(exc);
        }
    
        // Return the task to represent the asynchronous operation
        return tcs.Task;
    }

    public by msdn modified Jan 12, 2015  1556  0  7  0

    SendMessage: Send SMTP message. Most of the parameters are stored in the SSO.

    Send SMTP message. Most of the parameters are stored in the SSO. Text of the mail Message send in attachment
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net.Mail;
    using System.Net.Mime;
    using System.IO;
    using System.Xml;
    
    /// <summary>
    /// Send SMTP message.
    /// Most of the parameters are stored in the SSO.
    /// </summary>
    /// <param name="messageText">Text of the mail</param>
    /// <param name="XLANGMessage">Message send in attachment</param>
    public static void SendMessage(string messageText, Stream streamAttachment)
    {
        string to;
        string from;
        string cc;
        string subject;
        string host;
        int smtpPort;
        string username;
        string password;
        GetSmtpParams(out to, out from, out cc, out subject, out host, out smtpPort, out username, out password);
    
        MailMessage message = new MailMessage(from, to);
        message.Subject = subject;
        message.Body = messageText;
        message.IsBodyHtml = true;
    
        System.Net.Mime.ContentType customStreamAttachmentContentType = new System.Net.Mime.ContentType();
        Attachment attachment = new Attachment(streamAttachment, MediaTypeNames.Application.Octet);
        //attachment.TransferEncoding = TransferEncoding.Base64;
        message.Attachments.Add(attachment);
    
        SmtpClient client = new SmtpClient(host, smtpPort);
        client.Credentials = new System.Net.NetworkCredential(username, password);
    
        client.Send(message);
    }

    public by msdn modified Jan 12, 2015  1792  1  6  0

    SendTask: Sends an e-mail message asynchronously.

    Sends an e-mail message asynchronously. The client. A MailMessage that contains the message to send. A String that contains the address information of the message sender. A String that contains the address that the message is sent to. A String that contains the subject line for the message. A String that contains the message body. A user-def
    using System.Net.Mail;
    using System.Threading.Tasks;
    
    /// <summary>Sends an e-mail message asynchronously.</summary>
    /// <param name="smtpClient">The client.</param>
    /// <param name="message">A MailMessage that contains the message to send.</param>
    /// <param name="from">A String that contains the address information of the message sender.</param>
    /// <param name="recipients">A String that contains the address that the message is sent to.</param>
    /// <param name="subject">A String that contains the subject line for the message.</param>
    /// <param name="body">A String that contains the message body.</param>
    /// <param name="userToken">A user-defined object stored in the resulting Task.</param>
    /// <returns>A Task that represents the asynchronous send.</returns>
    public static Task SendTask(this SmtpClient smtpClient, string from, string recipients, string subject, string body, object userToken)
    {
        return SendTaskCore(smtpClient, userToken, tcs => smtpClient.SendAsync(from, recipients, subject, body, tcs));
    }

    external by escribano modified Oct 28, 2015  1950  1  3  0

    golang send mail net/smtp SMTP

    golang send mail net/smtp SMTP: sendMail.go
    Go
    package main
    
    import (
    
      "log"
    	"net/mail"
    	"encoding/base64"
    	"net/smtp"
    	"fmt"
    	"strings"
    )
    
    func encodeRFC2047(String string) string{
    	// use mail's rfc2047 to encode any string
    	addr := mail.Address{String, ""}
    	return strings.Trim(addr.String(), " <>")
    }
    
    
    func main() {
    	// Set up authentication information.
    
    	smtpServer := "smtp.163.com"
    	auth := smtp.PlainAuth(
    		"",
    		"fledna@163.com",
    		"password*******",
    		smtpServer,
    	)
    
    	from := mail.Address{"监控中心", "fledna@163.com"}
    	to := mail.Address{"收件人", "name@139.com"}
    	title := "当前时段统计报表"
    
    	body := "报表内容一切正常";
    
    	header := make(map[string]string)
    	header["From"] = from.String()
    	header["To"] = to.String()
    	header["Subject"] = encodeRFC2047(title)
    	header["MIME-Version"] = "1.0"
    	header["Content-Type"] = "text/plain; charset=\"utf-8\""
    	header["Content-Transfer-Encoding"] = "base64"
    
    	message := ""
    	for k, v := range header {
    		message += fmt.Sprintf("%s: %s\r\n", k, v)
    	}
    	message += "\r\n" + base64.StdEncoding.EncodeToString([]byte(body))
    
    	// Connect to the server, authenticate, set the sender and recipient,
    	// and send the email all in one step.
    	err := smtp.SendMail(
    		smtpServer + ":25",
    		auth,
    		from.Address,
    		[]string{to.Address},
    		[]byte(message),
    		//[]byte("This is the email body."),
    	)
    	if err != nil {
    		log.Fatal(err)
    	}
    }
    
    
    
    • Public Snippets
    • Channels Snippets