working on it ...

Filters

Explore Public Snippets

Sort by

Found 16k snippets matching: send

    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 ekarakas modified Aug 29, 2013  205611  3  5  0

    Send HTML Emails With PHP

    Send Hassle Free and Dependable HTML Emails With PHP
    function htmlmail($to, $subject, $message, $headers = NULL)
    {
    $mime_boundary = md5(time());
         
    $headers .= "\nMessage-ID: <" . time() . " TheSystem@{$_SERVER['SERVER_NAME']}>\n";
    $headers .= "X-Mailer: PHP " . phpversion() . "\n";
    $headers .= "MIME-Version: 1.0\n";
    $headers .= "Content-Type: multipart/alternative;boundary={$mime_boundary}\n\n";
         
    $newmessage = "This is a multi-part message in MIME format.";
    $newmessage .= "\n\n--{$mime_boundary}\n";
    $newmessage .= "Content-type: text/plain;charset=utf-8\n\n";
    $newmessage .= strip_tags(str_replace(array('<br>', '<br />'), "\n", $message)) . "\n\n";
         
    $newmessage .= "\n\n--{$mime_boundary}\n";
    $newmessage .= "Content-type: text/html;charset=utf-8\n\n";
         
    // prepended HTML
    $newmessage .= '<body style="margin:0"><table width="100%" height="100%" border="0" cellpadding="0" cellspacing="0"><tr><td bgcolor="#ffffff" valign="top"><table width="750" border="0" cellpadding="0" cellspacing="0" align="center"><tr><td bgcolor="#ffffff" width="750">';
         
    // HTML message that was passed to this function
    $newmessage .= $message;
         
    // appended HTML
    $newmessage .= '</td></tr></table></td></tr></table></body>';
         
    return mail($to, $subject, $newmessage, $headers);
    }
    

    public by lbottaro modified Mar 26, 2015  172467  10  6  0

    curl to send a GET HTTP request with query parameters

    Try to perform a GET HTTP to snip2code server, to list the public snippets in Channels. URL example to get: https://www.snip2code.com/Explore/InChannel?q=test&sort=0&direction=1 Options: -d: list all query parameters -G: perform GET verb
    curl -v -L -G -d "q=test&sort=0&direction=1" https://www.snip2code.com/Explore/InChannel                               

    public by phuonght modified Jan 23, 2016  212035  0  3  0

    A small script to make recording http live streams (HLS, those streams that work on iOS devices) nicer on a Mac. Script records the stream for a defined period of time and sends the user notifications if anything goes wrong and once it's done.

    A small script to make recording http live streams (HLS, those streams that work on iOS devices) nicer on a Mac. Script records the stream for a defined period of time and sends the user notifications if anything goes wrong and once it's done.: HLS_dvr.sh
    # required: ffmpeg (e.g. from homebrew), terminal-notifier from https://github.com/alloy/terminal-notifier 
    # you can schedule this with launchd to run e.g. weekly
    
    # Specify in seconds how long the script should record (default here is 1 hour).
    seconds=3600
    
    # Date format for the recording file name
    DATE=`date "+%d-%m-%y_%H-%M"`
    
    # start ffmpeg recording
    ffmpeg -re -i http://website.com/playlist.m3u8 -c copy -bsf:a aac_adtstoasc recording_$DATE.mp4 &
    
    # notification that recording has started
    if [ "$(pgrep -P $$ 'ffmpeg')" ]
    then
    	/Applications/terminal-notifier.app/Contents/MacOS/terminal-notifier -title 'ffmpeg' -message "is recording now" -sender 'com.apple.Terminal'
    else
    	/Applications/terminal-notifier.app/Contents/MacOS/terminal-notifier -title 'ffmpeg' -message "is not recording!" -sound Funk -sender 'com.apple.Terminal'
    	exit 42
    fi
    
    # check every 30 seconds for $seconds to make sure ffmpeg is still running
    START=`date +%s`
    while [ $(( $(date +%s) - $seconds )) -lt $START ]; do
    	if [ -z "$(pgrep -P $$ 'ffmpeg')" ]
        	then
           		/Applications/terminal-notifier.app/Contents/MacOS/terminal-notifier -title 'ffmpeg' -message "is no longer running" -sound Funk -sender 'com.apple.Terminal'
      	fi
    	sleep 30
    done
    
    # notification when time is up
    /Applications/terminal-notifier.app/Contents/MacOS/terminal-notifier -title 'ffmpeg' -message "recording finished" -sound default -sender 'com.apple.Terminal'
    
    # stop ffmpeg (using this because stopping ffmpeg via -t for duration turned out to be extremely unreliable)
    kill $(pgrep -P $$ 'ffmpeg')
    
    
    

    public by cghersi @ MailUp API DEV modified Jan 20, 2015  206772  8  6  1

    MailUp REST API - How to subscribe to a particular list several contacts with the "Confirmed Optin" Procedure

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void SubcribeRecipientsWithDoubleOptin(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Subscribe recipients:
        int idList = 1;
        List<ConsoleRecipientItem> recipients = new List<ConsoleRecipientItem>();
        ConsoleRecipientItem recipient1 = new ConsoleRecipientItem()
        {
            Email = "test1@mailup.com",
            Name = "First New Recipient" + DateTime.Now.ToFileTimeUtc(),
            MobileNumber = "3331234567",
            MobilePrefix = "39",
            Fields = new List<ConsoleRecipientDynamicFieldItem>()
            {
                new ConsoleRecipientDynamicFieldItem() { Id = 1, Value = "Name1_" + DateTime.Now.ToFileTimeUtc() },
                new ConsoleRecipientDynamicFieldItem() { Id = 2, Value = "LastName1_" + DateTime.Now.ToFileTimeUtc() }
                //here you can add all the fields you want to add...
            }
        };
        ConsoleRecipientItem recipient2 = new ConsoleRecipientItem()
        {
            Email = "test2@mailup.com",
            Name = "Second New Recipient" + DateTime.Now.ToFileTimeUtc(),
            MobileNumber = "3337654321",
            MobilePrefix = "39",
            Fields = new List<ConsoleRecipientDynamicFieldItem>()
            {
                new ConsoleRecipientDynamicFieldItem() { Id = 1, Value = "Name2_" + DateTime.Now.ToFileTimeUtc() },
                new ConsoleRecipientDynamicFieldItem() { Id = 2, Value = "LastName2_" + DateTime.Now.ToFileTimeUtc() }
                //here you can add all the fields you want to add...
            }
        };
        recipients.Add(recipient1);
        recipients.Add(recipient2);
        int subscriptionResult = 0;
        try
        {
            subscriptionResult = client.AddRecipientsToList(idList, recipients, true);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
        // 2.1) wait for the end of import task:
        if (subscriptionResult > 0)
        {
            Console.WriteLine("Recipients Import started; import ID:" + subscriptionResult);
    
            //optionally we can check the import status:
            bool completed = false;
            do
            {
                ConsoleImportStatus importStatus = client.CheckImportStatus(subscriptionResult);
                if (importStatus == null)
                {
                    Console.WriteLine("Cannot check the import status for import task #" + subscriptionResult);
                    return;
                }
                completed = importStatus.Completed;
            } while (!completed);
            Console.WriteLine("Recipients Added!");
        }
        else
        {
            Console.WriteLine("An error occurred while adding the recipients.");
            return;
        }
    
        // 3) Retrieve the sendingID of the confirmation email related to the previous task:
        int sendingID = -1;
        try
        {
            sendingID = client.GetSendingIDForImport(subscriptionResult);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot retrieve sending ID due to " + ex.Message);
            return;
        }
        if (sendingID <= 0)
        {
            Console.WriteLine("Cannot retrieve sending ID.");
            return;
        }
    
        // 4) Send the confirmation email:
        EmailSendingItem sendingResult = null;
        try
        {
            sendingResult = client.SendEmailMessage(sendingID);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot send email due to " + ex.Message);
            return;
        }
        if (sendingResult == null)
            Console.WriteLine("Cannot send confirmation email.");
        else
            Console.WriteLine("Confirmation email sent!");
    }
                

    public by Geometry modified Jul 31, 2016  148352  0  3  0

    GetCommandBuffer: Gets the bytes representing the specified command. returned buffer can be used to streamline multiple writes into one Write on the Socket using the <see cref="M:Enyim.Caching.Memcached.PooledSocket.Write(IList&lt;ArraySegment&lt;b...

    Gets the bytes representing the specified command. returned buffer can be used to streamline multiple writes into one Write on the Socket using the The command to be converted. The buffer containing the bytes representing the command. The command must be terminated by \r\n. The Nagle algorithm is disabled on the socket to speed things up, so it's
    C#
    using System;
    using System.IO;
    using System.Text;
    using System.Collections.Generic;
    
    /// <summary>
    /// Gets the bytes representing the specified command. returned buffer can be used to streamline multiple writes into one Write on the Socket
    /// using the <see cref="M:Enyim.Caching.Memcached.PooledSocket.Write(IList&lt;ArraySegment&lt;byte&gt;&gt;)"/>
    /// </summary>
    /// <param name="value">The command to be converted.</param>
    /// <returns>The buffer containing the bytes representing the command. The command must be terminated by \r\n.</returns>
    /// <remarks>The Nagle algorithm is disabled on the socket to speed things up, so it's recommended to convert a command into a buffer
    /// and use the <see cref="M:Enyim.Caching.Memcached.PooledSocket.Write(IList&lt;ArraySegment&lt;byte&gt;&gt;)"/> to send the command and the additional buffers in one transaction.</remarks>
    public unsafe static IList<ArraySegment<byte>> GetCommandBuffer(string value)
    {
    	var data = new ArraySegment<byte>(Encoding.ASCII.GetBytes(value));
    
    	return new ArraySegment<byte>[] { data };
    }

    public by dave83 modified Mar 27, 2014  2718  1  6  2

    How to send messages using MessageProducer in JMS

    The code shows how to send messages using a MessageProducer in Java Message Service. Destination object is the queue where to send, read as JNDI lookup queue. The Session used is not transactional and auto acknowledged. Note the delivery mode of send method is set to Persistent, so the message will be persisted by JMS broker and its delivery wil
    // Load JNDI properties
    Properties properties = new Properties();            
    properties.load(this.getClass().getResourceAsStream("my.properties"));
    
    //Create the initial context       
    Context ctx = new InitialContext(properties);
    		            
    // look up destination and connection factory
    Destination destination = (Destination)ctx.lookup("myQueue");
    ConnectionFactory conFac = (ConnectionFactory)ctx.lookup("Connectionfactory");
    Connection connection = conFac.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer messageProducer = session.createProducer(destination);
    TextMessage message;
    
    // Send a series of messages in a loop
    for (int i = 1; i < 100; i++)
    {
        message = session.createTextMessage("Message " + i);
        messageProducer.send(message, DeliveryMode.PERSISTENT, Message.DEFAULT_PRIORITY, Message.DEFAULT_TIME_TO_LIVE);             
    }

    public by lbottaro modified Jan 23, 2013  5444  30  8  1

    Send Email in python

    This method sends an email to a recipients list. The method can generate a message both as HMTL and simple TXT and attach also some file to email. Note the use of MIME values to define which format being used.
    #!/usr/bin/python
    import os
    import sys
    
    #Imports for HTML email format
    import smtplib
    from email.mime.multipart import MIMEMultipart
    from email.mime.text import MIMEText
    from email import Encoders
    from email.MIMEBase import MIMEBase
    from subprocess import Popen, PIPE, STDOUT
    
    use_email_format_html = False
    # This function sends an email with the specified arguments
    def sendmail(recipients, subject, text, attachedFiles=[]):
        emailFrom = "userSender"
        emailTo = recipients
        msg = MIMEMultipart('alternative')
        msg['Subject'] = subject
        msg['From'] = emailFrom
        msg['To'] = emailTo
        if use_email_format_html: 
            msg.attach(MIMEText(text, 'html'))
        else:
            msg.attach(MIMEText(text, 'plain'))
        if attachedFiles:
            print 'Attached files...'
            # attach a file
            for file in attachedFiles:
                part = MIMEBase('application', "octet-stream")
                print file
                part.set_payload( open(file,"rb").read() )
        	      Encoders.encode_base64(part)
                part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(file))
                msg.attach(part)
    
        # Send the message via local SMTP server.
        s = smtplib.SMTP('localhost')
        # sendmail function takes 3 arguments: sender's address, recipient's address
        s.sendmail(emailFrom, emailTo.split(","), msg.as_string())
        s.quit()
    
    ######
    # MAIN - USAGE
    ######
    recipients = "email01@email.com, email02@email.com"
    subject = "Python email"
    text='<font color="red"><b>' + "BLA BLA BLA" + "</b></font>"
    attachedFiles = list()
    attachedFiles.append("/path/my/file2")
    attachedFiles.append("/path/my/file2")
    sendmail(recipients, subject, text, attachedFiles)        
    use_email_format_html = True
    sendmail(recipients, subject, text, attachedFiles)        

    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 Jan 15, 2015  1865  27  6  1

    MailUp REST API - How to create and send an email to a specific recipient.

    This snippet takes advantage of the MailUp .NET SDK to setup the secure communication towards the server through OAuth2 two leg authentication. You can start digging into the MailUP API world by reading this content: http://help.mailup.com/display/mailupapi/REST+API An instance of MailUpClient class is able to manage one user at a time. A MailU
    public static void CreateAndSendEmail(string clientID, string clientSecret, string username, string password)
    {
        // 1) Setup the MailUp Client:
        MailUpClient client = new MailUpClient(clientID, clientSecret);
        try
        {
            client.RetrieveAccessToken(username, password);
        }
        catch (MailUpException ex)
        {
            Console.WriteLine("Unable to access the service due to " + ex.Message);
            return;
        }
    
        // 2) Create the message:
        int idList = 1;
        string subject = "Test Creation Email";
        ConsoleMessageDetailItem message = new ConsoleMessageDetailItem()
        {
            Content = "Test Content",
            Embed = false,
            idList = idList,
            IsConfirmation = false,
            Notes = "Bunch of test notes",
            Subject = subject,
            TrackingInfo = new ConsoleEmailTrackingInfo() { Enabled = true, Protocols = new List<string>() { "http" } }
        };
        ConsoleMessageItem createMsgResult = null;
        try
        {
            createMsgResult = client.CreateMessage(idList, message);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Unable to create the message due to " + ex.Message);
            return;
        }
        if (createMsgResult == null)
        {
            Console.WriteLine("Unable to create the message");
            return;
        }
    
        // 3) Send the just created message:
        EmailSendToRecipientRequest request = new EmailSendToRecipientRequest()
        {
            Email = "recipient@mailup.com",
            idMessage = createMsgResult.idMessage.Value
        };
        MailMessageSendResponse result = null;
        try
        {
            result = client.SendEmailMessage(request);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Cannot perform the operation due to " + ex.Message);
            return;
        }
    
        // 4) Print results:
        if (result != null)
            Console.WriteLine("Message sent to " + result.Sent + " recipient(s).");
        else
            Console.WriteLine("An error occurred while sending the message.");
    }
    
    • Public Snippets
    • Channels Snippets